请原谅我没有对此做更多具体说明。我有一个奇怪的错误。在文档加载后,我循环了一些原来具有的元素data-itemname="",并使用设置了这些值.attr("data-itemname", "someValue")。
问题:当我以后遍历那些元素时,如果elem.data().itemname我知道"",则得到,但如果我知道,则elem.attr("data-itemname")得到"someValue"。就像jQuery的.data()getter只获取最初设置为包含某些值的元素,但是如果它们最初为空,然后又被设置,则以后.data()不会获取该值。
我一直在尝试重新创建此错误,但未能成功。
编辑
我已经重新创建了错误!http://jsbin.com/ihuhep/edit#javascript,html,live
此外,来自上方链接的摘录...
JS:
var theaters = [
{ name: "theater A", theaterId: 5 },
{ name: "theater B", theaterId: 17 }
];
$("#theaters").html(
$("#theaterTmpl").render(theaters)
);
// DOES NOT WORK - .data("name", "val") does NOT set the val
var theaterA = $("[data-theaterid='5']");
theaterA.find(".someLink").data("tofilllater", "theater5link"); // this does NOT set data-tofilllater
$(".someLink[data-tofilllater='theater5link']").html("changed link text"); // never gets changed
// WORKS - .attr("data-name", "val") DOES set val
var theaterB = $("[data-theaterid='17']");
theaterB.find(".someLink").attr("data-tofilllater", "theater17link"); // this does set data-tofilllater
$(".someLink[data-tofilllater='theater17link']").html("changed link text");
HTML:
<body>
<div id="theaters"></div>
</body>
<script id="theaterTmpl" type="text/x-jquery-tmpl">
<div class="theater" data-theaterid="{{=theaterId}}">
<h2>{{=name}}</h2>
<a href="#" class="someLink" data-tofilllater="">need to change this text</a>
</div>
</script>
elem.data("itemname")不是elem.data().itemname?
elem.data().itemname = somevalue;,不会更改基础数据。)