ยกโทษให้ฉันที่ไม่เจาะจงเรื่องนี้มากขึ้น ฉันมีข้อผิดพลาดแปลก ๆ หลังจากโหลดเอกสารแล้วฉันก็วนองค์ประกอบบางอย่างที่มีอยู่เดิมdata-itemname=""
และตั้งค่าเหล่านั้นโดยใช้.attr("data-itemname", "someValue")
.
ปัญหา: เมื่อฉันห่วงภายหลังผ่านองค์ประกอบเหล่านั้นถ้าฉันทำelem.data().itemname
ฉันได้รับ""
แต่ถ้าฉันทำฉันได้รับelem.attr("data-itemname")
"someValue"
เหมือนกับ.data()
getter ของ jQuery รับเฉพาะองค์ประกอบที่ตั้งค่าไว้ในตอนแรกเพื่อให้มีค่าบางอย่าง แต่ถ้าเดิมว่างเปล่าและตั้งค่าในภายหลัง.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>