更改 html 数据属性值 [英] Change html data attribute value

查看:25
本文介绍了更改 html 数据属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$(document).ready( function () {$("#bla").on("点击", function () {警报( $(this).data('bla') );$(this).attr('data-bla', "2");});});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script><div id="bla" data-bla="1">按钮

因此,我需要将 data-bla 值从1"更改为2",但正如您所看到的,值未更新并且每次单击按钮时都会提醒默认值1".

我做错了什么?

解决方案

data() is not data-* 的访问器函数属性.它是元素的 jQuery 数据缓存的访问器,该元素仅从 data-* 属性初始化.

如果你想读取data-bla属性的值,使用attr("data-bla"),而不是data("bla").如果要设置bla数据项,使用data("bla", newValue),而不是attr("data-bla", newValue).

例如,获取和设置都使用attr()获取和设置都使用data(),但不要'不要混合使用它们,因为它们管理不同的事物.

使用attr():

$(document).ready( function () {$("#bla").on("点击", function () {alert( $(this).attr('data-bla') );$(this).attr('data-bla', "2");});});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script><div id="bla" data-bla="1">按钮

使用data():

$(document).ready( function () {$("#bla").on("点击", function () {警报( $(this).data('bla') );$(this).data('bla', "2");});});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script><div id="bla" data-bla="1">按钮

$(document).ready( function () {

  $("#bla").on( "click", function () {
  
        alert( $(this).data('bla') );
  	    $(this).attr('data-bla', "2");  
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="bla" data-bla="1">
  button
</div>

So, I need change data-bla value from "1" to "2", but as you can see, value not updated and every click on button, alerts default value "1".

What did I do wrong?

解决方案

data() is not an accessor function for data-* attributes. It's an accessor for jQuery's data cache for the element, which is only initialized from data-* attributes.

If you want to read the data-bla attribute's value, use attr("data-bla"), not data("bla"). If you want to set the bla data item, use data("bla", newValue), not attr("data-bla", newValue).

E.g., use attr() for both get and set, or use data() for both get and set, but don't mix them, because they manage different things.

Using attr():

$(document).ready( function () {

  $("#bla").on( "click", function () {
  
        alert( $(this).attr('data-bla') );
  	    $(this).attr('data-bla', "2");  
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="bla" data-bla="1">
  button
</div>

Using data():

$(document).ready( function () {

  $("#bla").on( "click", function () {
  
        alert( $(this).data('bla') );
  	    $(this).data('bla', "2");  
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="bla" data-bla="1">
  button
</div>

这篇关于更改 html 数据属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆