简体   繁体   English

将一个元素的分配ID值更改为另一个元素的data属性

[英]Change Assign ID Value of an element to the data attribute of another element

I have several HTML link elements, which all have a unique number ID. 我有几个HTML链接元素,它们都有唯一的数字ID。

These are all stored in a wrapper, which uses a data attribute called "data-color". 这些都存储在包装器中,该包装器使用称为“ data-color”的数据属性。

When the user clicks on the links, I want the data-color to take on the number ID of the link. 当用户单击链接时,我希望数据颜色采用链接的数字ID。

I thought I could use data(), but it doesn't seem to work. 我以为可以使用data(),但似乎不起作用。

Here is a JSFIDDLE . 这是一个JSFIDDLE

Here is my HTML: 这是我的HTML:

<div id="wrapper" data-color="01">

<span>Color Box</span>

<a class="ThumbnailBox" href="#" id="02">02</a>
<a class="ThumbnailBox" href="#" id="03">03</a>
<a class="ThumbnailBox" href="#" id="04">04</a>
<a class="ThumbnailBox" href="#" id="05">05</a>
<a class="ThumbnailBox" href="#" id="06">06</a>

</div>

Here is my Jquery: 这是我的Jquery:

(function ($) {
    $(document).ready(function () {

        $(".ThumbnailBox").click(function () {
            selectedcolor = $(this).attr('id');
            $('#wrapper').data('datacolor', selectedcolor);

        });
    });

})(jQuery);

try something like this, you don't have to use data- to use it 尝试这样的事情,您不必使用数据即可使用

$(".ThumbnailBox").click(function () {
    $('#wrapper').data('color', this.id);
});

to change the value in dom than use attr 更改dom中的值而不是使用attr

$('#wrapper').attr('data-color', this.id);

The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery) 数据属性在第一次访问数据属性时被提取,然后不再被访问或变异(所有数据值然后内部存储在jQuery中)

you just try this code it working fine.. 您只需尝试此代码即可正常工作。

$(".ThumbnailBox").click(function () {
selectedcolor = $(this).attr('id');
    alert(selectedcolor)
$('#wrapper').attr('data-color', selectedcolor);
});

Here is updated fiddle http://jsfiddle.net/dLQHs/3/ 这是更新的小提琴http://jsfiddle.net/dLQHs/3/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM