很抱歉我没有更详细的描述。我有一个很奇怪的bug。文档加载后,我循环一些初始带有data-itemname=""
属性的元素,并使用.attr("data-itemname", "someValue")
设置这些值。
问题:当以后循环这些元素时,如果执行elem.data().itemname
,我得到的是""
,但如果执行elem.attr("data-itemname")
,我会得到"someValue"
。这就像jQuery的.data()
获取器只能获取最初被设置为包含某个值的元素,但如果它们最初为空,然后稍后设置,那么.data()
无法在以后获取该值。
我一直在尝试重现这个bug,但一直没成功。
编辑
我已经重新创建了这个bug!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"></script>
elem.data("itemname")
而不是elem.data().itemname
吗? - Hoganelem.data().itemname
可以让你读取值,但它不能让你设置值。因此,elem.data().itemname = somevalue;
不会改变底层数据。 - Hogan