Thứ lỗi cho tôi vì đã không nói rõ hơn về điều này. Tôi có một lỗi kỳ lạ như vậy. Sau khi tải tài liệu, tôi lặp lại một số phần tử mà ban đầu có data-itemname=""
và tôi đặt các giá trị đó bằng cách sử dụng .attr("data-itemname", "someValue")
.
Vấn đề: Sau này khi tôi lặp qua các phần tử đó, nếu tôi làm elem.data().itemname
, tôi nhận được ""
, nhưng nếu tôi làm elem.attr("data-itemname")
, tôi nhận được "someValue"
. Nó giống như .data()
getter của jQuery chỉ nhận các phần tử được đặt ban đầu để chứa một số giá trị, nhưng nếu ban đầu chúng trống và sau đó được đặt, thì sau .data()
này sẽ không nhận được giá trị.
Tôi đã cố gắng tạo lại lỗi này nhưng không thể.
Biên tập
Tôi đã tạo lại lỗi! http://jsbin.com/ihuhep/edit#javascript,html,live
Ngoài ra, các đoạn trích từ liên kết trên ...
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")
không elem.data().itemname
?
elem.data().itemname = somevalue;
đó không thay đổi dữ liệu cơ bản.)