【问题标题】:.data() not working as expected.data() 没有按预期工作
【发布时间】:2012-06-10 11:55:54
【问题描述】:

我有密码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script src="jquery.js"></script><script>
$(function(){
$(".classy").data("read","hi");//Not working .working is$("div").attr("data-read","hi");

});</script>
<style>
.classy[data-read='hello']{background:#000;}.classy[data-read='hi']{background:#fff;}</style>
</head>

<body>
<div class="classy" data-read="hello">a</div>
</body>
</html>

发生的情况是,当文档准备好时,.classy 的数据读取属性更改为 hi。我有 .classy[data-read='hi'] 的 css 样式设计,但是当我使用 .data() 方法来操作数据时它不起作用 -读取属性。当我使用.attr() 方法来操作数据读取时它可以工作。为什么?

【问题讨论】:

  • 因为.data() 没有设置属性 - 它用于存储与 DOM 元素相关的信息
  • 所以,在这种情况下我不能使用 .data()
  • 查看更新的代码,现在你会推荐什么
  • 你错过了我的观点 - 我的意思是改变类来改变 CSS 属性 - 不要使用 .data().attr()
  • dude 的 .attr() 有什么问题

标签: javascript jquery html css attr


【解决方案1】:

您误解了data-xxx 的用途。它用于填充 HTML 标记中的数据,以后可以使用 jQuery 通过使用 .data() 来检索这些数据。

例子:

​console.log($('.classy').data('read'));​​​​​​​​​

$(".classy").data("read","hi");

​console.log($('.classy').data('read'));​​​​​​​​​

输出:

hello
hi

稍后更改该数据时,它不会再更改元素的data-xxx 属性;这也使它不适合条件 CSS 处理。

您应该将.addClass().toggleClass().removeClass() 与CSS 类选择器结合使用以使其工作。

【讨论】:

  • @Somebodyisintrouble 确定,为什么不 :) 添加到答案中
猜你喜欢
  • 2021-10-19
  • 2020-03-18
  • 2012-06-14
  • 2014-11-15
  • 1970-01-01
  • 2012-07-02
  • 2011-09-07
  • 2013-03-03
  • 2015-05-18
相关资源
最近更新 更多