jQuery数据与Attr?

JavaScript

Eva斯丁

2020-03-12

使用之间$.data$.attr使用时在用法上有什么区别data-someAttribute

我的理解是,$.data它存储在jQuery的内部$.cache,而不是DOM。因此,如果要$.cache用于数据存储,则应使用$.data如果要添加HTML5数据属性,则应使用$.attr("data-attribute", "myCoolValue")

第1196篇《jQuery数据与Attr?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
小小神奇 2020.03.12

您可以使用data-*属性嵌入自定义数据。这些data-*属性使我们能够在所有HTML元素上嵌入自定义数据属性。

jQuery .data() method allows you to get/set data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks.

jQuery .attr() method get/set attribute value for only the first element in the matched set.

Example:

<span id="test" title="foo" data-kind="primary">foo</span>

$("#test").attr("title");
$("#test").attr("data-kind");
$("#test").data("kind");
$("#test").data("value", "bar");

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android