更改数据未知属性值 [英] change data-unknown attribute value
问题描述
我有3个div的页面,每个div例如有2个数据属性
i have page with 3 divs each div has 2 data-attribute for example
<div class="div1" data-10="some value" data-30="some value"></div>
我可以通过此方法更改数据属性的值
i can change the value of the data attribute by this method
$('.div1').attr('data-30', 'some changed values');
但是问题在于data属性的第二部分是未知的(数据未知数)
but the problem is that the second part of the data attribute is unknown (data-unknown number)
我不知道此符号"-
"后面的数字可能是30,40,50 or what ever
,所以我如何选择要更改其值的数据属性?
i don't know the number after this sign "-
" it may will be 30,40,50 or what ever
so how can i select the data attribute that i want to change it's value ?
我只想更改第二个数据属性,我不在乎第一个
i only want to change the second data-attribute , i don't care about the first one
我该怎么办?
在此先感谢
推荐答案
修改,更新
仍然不会更改data-attr的值
still doesn't change the value of the data-attr
jQuery .data()
不会更改data-*
属性,请参见 jQuery的. data()不会将属性附加到DOMElement , jQuery Data vs Attr? .
jQuery .data()
does not change data-*
attributes , see jQuery's .data() doesn't append attribute to DOMElement , jQuery Data vs Attr? .
尝试利用 HTMLElement.dataset
(ie11 )设置实际的html
dataset
,例如
elem[0].dataset[key] = "margin-top:100px";
只想更改第二个数据属性,我不在乎 第一个
only want to change the second data-attribute , i don't care about the first one
尝试使用.data()
,$.map()
var index = 0, elem = $(".div1");
$.map(elem.data(), function(value, key) {
++index;
// if `index` is `2`
if (index === 2) {
// do stuff with second `data-*` attribute
// change the value of that data-attribute
// for example to `margin-top:100px`
elem.data(key, "margin-top:100px");
// still doesn't change the value of the data-attr
elem[0].dataset[key] = "margin-top:100px";
}
});
console.log(elem.data(), elem[0].dataset["30"]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="div1" data-10="some value" data-30="some value"></div>
这篇关于更改数据未知属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!