jQuery .data()不起作用,但.attr()可以
原谅我没有更具体的这一点。我有这么奇怪的错误。在doc加载之后,我循环了一些原来的元素data-itemname="",并使用它来设置这些值.attr("data-itemname", "someValue")。
问题:当我后来循环通过这些元素时,如果我这样做elem.data().itemname,我会得到"",但如果我这样做elem.attr("data-itemname"),我会得到"someValue"。这就像jQuery的.data()getter只获取最初设置为包含某些值的元素,但如果它们最初是空的,稍后设置,则稍后.data()不会获得该值。
我一直试图重新创建这个bug,但一直没能。
编辑
另外,链接上面的片段......
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 valvar 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 valvar 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: