请原谅我没有在这件事上说得更具体。我有一只奇怪的虫子。在文档加载之后,我循环一些最初具有data-itemname=""的元素,并使用.attr("data-itemname", "someValue")设置这些值。
问题:当我稍后循环这些元素时,如果我执行elem.data().itemname,我得到"",但是如果我执行elem.attr("data-itemname"),则得到"someValue"。这就像jQuery的.data() getter只获取最初设置为包含一些值的元素,但是如果它们最初是空的,然后是设置的,那么.data()以后就不会得到这个值。
我一直试图重新创建这个bug,但一直未能。
编辑
我重新创建了这个bug!http://jsbin.com/ihuhep/edit#javascript,html,live
还有上面链接上的片段..。
联署材料:
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>发布于 2018-07-23 14:13:11
.attr("data-itemname", "someValue")修改DOM。
.data("itemname", "someValue")修改jQuery缓存。
要使它在后面的Javascript中工作,另外在CSS中,您必须同时设置这两种方式。
theaterA.find(".someLink").attr("data-itemname", "someValue");
theaterA.find(".someLink").data("itemname", "someValue");https://stackoverflow.com/questions/8707226
复制相似问题