使用 jQuery 更新数据属性的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7874320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:23:40  来源:igfitidea点击:

Updating the value of data attribute using jQuery

jquery

提问by Ibrahim Azhar Armar

I have the following HTML code:

我有以下 HTML 代码:

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

I want to update the value of the srcand data-blockattributes using jQuery. How do I do this?

我想使用 jQuery更新srcdata-block属性的值。我该怎么做呢?

Update:As I have many image elements, I want to update the value of a specific image by using data-id.

更新:由于我有很多图像元素,我想使用data-id.

回答by MarioRicalde

$('.toggle img').data('block', 'something');
$('.toggle img').attr('src', 'something.jpg');

Use jQuery.dataand jQuery.attr.

使用jQuery.datajQuery.attr

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

为了大家理解,我分别给大家展示一下。

回答by JP Hellemons

$('.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');

回答by Alp Altunel

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

我想更改 div 的宽度和高度。数据属性没有改变它。相反,我使用:

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.

这已经设置了。

回答by Paul Verbeek-Mast

$('.toggle img').data('block', 'something').attr('src', 'something.jpg');