【发布时间】:2012-02-01 04:41:00
【问题描述】:
请原谅我没有更具体地说明这一点。我有这样一个奇怪的错误。加载文档后,我循环了一些最初具有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
另外,上面链接的sn-ps...
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 会让您读取值,但不会让您设置值。 (因此
elem.data().itemname = somevalue;不会更改基础数据。) -
@dkamins - 我已经重新创建了错误,请查看编辑后的版本。
标签: jquery