是否可以使用jQuery写入HTML data- *? [英] Is it possible to write to HTML data-* using jQuery?

查看:103
本文介绍了是否可以使用jQuery写入HTML data- *?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法相信这方面没有容易找到的答案,官方的文档只会让我迷惑。

I can't believe there's no easy-to-find answer for this, and the official documentation only serves to confuse me.

我有一个 div ,带有 data- 属性,让我们说 data-color ,我想在用户点击按钮时更改它。

I have a div with a data- attribute, let's say data-color, and I want to change it when the user clicks a button.

我想我会这样做:

$('.button').click(function(){
    $('.div-with-data').data('color', 'red')
})

但它不起作用。是否有可能实际写入数据 - 这样或只读?

But it doesn't work. Is it possible at all to actually write to data- like this or is it read only?

推荐答案

您的代码运行正常 - 它只是不更新​​DOM。 jQuery在内部缓存对象中存储 data 属性以获得更好的性能。您应该始终使用 data()来获取和设置这些属性,除非您有特殊原因需要在DOM中使用它。

Your code is working fine - it just doesn't update the DOM. jQuery stores data attributes in an internal cache object for better performance. You should always use data() to get and set these attributes, unless there is a specific reason you need it available in the DOM.

alert($('.div-with-data').data('color')); // = green

$('.button').click(function(){
  $('.div-with-data').data('color', 'red');
  alert($('.div-with-data').data('color')); // it's now red
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div-with-data" data-color="green">
    Foo
</div>

<button class="button">Click me</button>

这篇关于是否可以使用jQuery写入HTML data- *?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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