问题描述
看来jQuery 1.7.2并未为我更新DOM数据属性.给出以下标记:
It seems jQuery 1.7.2 isn't updating the DOM data attributes for me. Given the following markup:
<ul id="foo">
<li data-my-key="12345">ABCDEF</li>
</ul>
运行下面的JavaScript,我得到了一些意想不到的结果:
Running the JavaScript below, I get some results I'm not expecting:
$('#foo li:first').data('my-key') // Returns 12345 - Expected
$('#foo li[data-my-key="12345"]') // Returns the expected <li>
$('#foo li:first').data('my-key', '54321')
$('#foo li:first').data('my-key') // Returns 54321 - Expected
$('#foo li[data-my-key="54321"]') // Returns an empty array - Not expected
在进一步调查中,我注意到使用.data()函数(在Chrome 21.0.1180.81,Firebug 1.10中通过检查元素"验证)设置了新值后,DOM没有未被修改. 3和Firefox 14.0.1).
Upon further investigation, I noticed the DOM has not been modified after setting a new value using the .data() function (verified with "Inspect Element" in Chrome 21.0.1180.81, Firebug 1.10.3 and Firefox 14.0.1).
该行为在我的预期中是意外的,但这是jQuery数据起作用的预期方式吗?如果是这样,用jQuery更新data- *属性的适当方法是什么?只需使用attr()函数?
The behavior is unexpected from my prospective, but is this the intended way for jQuery data to function? If so, what is the appropriate way to update data-* attributes with jQuery? Simply use the attr() function?
推荐答案
$('#foo li[data-my-key="54321"]')
是属性选择器.
使用.data(..)
可以更改元素属性,这些元素如果不使用过滤器便无法选择.
Using .data(..)
changes the elements properties which you cannot select from without using a filter.
如果您想获得具有特定属性的所有元素,请执行以下操作(使用 filter(...)
):
If you want to get all the elements with a certain property you can do this (using filter(...)
):
$('#foo li').filter(function(index) {
return $(this).data('my-key') === 54321;
}); //returns all `#foo li` with data[my-key] === 54321
有关更多信息,请参见此处: .prop()与.attr()
这篇关于jQuery .data()不更新DOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!