原谅我没有更具体的这一点.我有这么奇怪的错误.在doc加载之后,我循环了一些原来的元素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
另外,链接上面的片段......
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 …Run Code Online (Sandbox Code Playgroud) 我只想从两个元素中获取几个属性.value从input元素获取属性按预期工作.问题是data-detail从button元素获取属性属性.它undefined在使用时返回.prop(),但在使用时按预期工作.attr().
任何人都可以解释我目睹的这种奇怪的行为吗?
HTML
<div class="formRow">
<label for="firstName">First name</label>
<div class="detailsControlBtns">
<button id="editFirstName" class="btn ctaBtn greenBtn editBtn">Edit</button>
<button class="btn ctaBtn greenBtn saveBtn" data-detail="firstName">Save</button>
<button id="closeFirstName" class="btn ctaBtn greyBtn closeBtn">Close</button>
</div>
<input type="text" id="firstName" name="firstName" value="[+firstName+]" readonly>
</div>
Run Code Online (Sandbox Code Playgroud)
JS
$(".saveBtn").on("click", function() {
var saveBtn = $(this);
// The following statement yields undefined. When using .attr() it works as expected.
var detail = saveBtn.prop("data-detail");
var relevantInput = saveBtn.parent().next();
// …Run Code Online (Sandbox Code Playgroud)