首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >jQuery .data()不起作用,但.attr()起作用

jQuery .data()不起作用,但.attr()起作用
EN

Stack Overflow用户
提问于 2012-01-03 02:14:34
回答 7查看 94.9K关注 0票数 127

请原谅我没有在这件事上说得更具体。我有一只奇怪的虫子。在文档加载之后,我循环一些最初具有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

还有上面链接上的片段..。

联署材料:

代码语言:javascript
运行
复制
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:

代码语言:javascript
运行
复制
<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>
EN

Stack Overflow用户

发布于 2018-07-23 14:13:11

.attr("data-itemname", "someValue")修改DOM。

.data("itemname", "someValue")修改jQuery缓存。

要使它在后面的Javascript中工作,另外在CSS中,您必须同时设置这两种方式。

代码语言:javascript
运行
复制
theaterA.find(".someLink").attr("data-itemname", "someValue");
theaterA.find(".someLink").data("itemname", "someValue");
票数 19
EN
查看全部 7 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8707226

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档