使用 jQuery 更新 data 属性的值

我有以下 HTML 代码:

<a class="toggle" href="#toggle">
<img src="app/css/images/tock.png" alt="No" data-id="4" data-block="1">
</a>

我想使用 jQuery 更新 srcdata-block属性的值?

更新: 由于我有许多图像元素,我想使用 data-id更新特定图像的值。

208024 次浏览
$('.toggle img').data('block', 'something');
$('.toggle img').attr('src', 'something.jpg');

Use jQuery.data and jQuery.attr.

I'm showing them to you separately for the sake of understanding.

$('.toggle img').data('block', 'something').attr('src', 'something.jpg');
$('.toggle img').each(function(index) {
if($(this).attr('data-id') == '4')
{
$(this).attr('data-block', 'something');
$(this).attr('src', 'something.jpg');
}
});

or

$('.toggle img[data-id="4"]').attr('data-block', 'something');
$('.toggle img[data-id="4"]').attr('src', 'something.jpg');

I want to change the width and height of a div. data attributes did not change it. Instead I use:

var size = $("#theme_photo_size").val().split("x");
$("#imageupload_img").width(size[0]);
$("#imageupload_img").attr("data-width", size[0]);
$("#imageupload_img").height(size[1]);
$("#imageupload_img").attr("data-height", size[1]);

be careful:

$("#imageupload_img").data("height", size[1]); //did not work

did not set it

$("#imageupload_img").attr("data-height", size[1]); // yes it worked!

this has set it.