Javascript jQuery 数据与 Attr?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7261619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:32:24  来源:igfitidea点击:

jQuery Data vs Attr?

javascriptjqueryhtmlcustom-data-attribute

提问by John B

What is the difference in usage between $.dataand $.attrwhen using data-someAttribute?

使用$.data$.attr使用时的用法有什么区别data-someAttribute

My understanding is that $.datais stored within jQuery's $.cache, not the DOM. Therefore, if I want to use $.cachefor data storage, I should use $.data. If I want to add HTML5 data-attributes, I should use $.attr("data-attribute", "myCoolValue").

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

回答by zzzzBov

If you are passing data to a DOM element from the server, you should set the data on the element:

如果您要从服务器向 DOM 元素传递数据,则应在该元素上设置数据:

<a id="foo" data-foo="bar" href="#">foo!</a>

The data can then be accessed using .data()in jQuery:

然后可以使用.data()jQuery访问数据:

console.log( $('#foo').data('foo') );
//outputs "bar"

However when you store data on a DOM node in jQuery usingdata, the variables are stored on the node object. This is to accommodate complex objects and references as storing the data on the node elementas an attribute will only accommodate string values.

但是,当您使用数据在 jQuery 中的 DOM 节点上存储数据时,变量将存储在节点对象上。这是为了容纳复杂的对象和引用,因为将数据存储在节点元素上作为属性将仅容纳字符串值。

Continuing my example from above:继续我上面的例子:
$('#foo').data('foo', 'baz');

console.log( $('#foo').attr('data-foo') );
//outputs "bar" as the attribute was never changed

console.log( $('#foo').data('foo') );
//outputs "baz" as the value has been updated on the object

Also, the naming convention for data attributes has a bit of a hidden "gotcha":

此外,数据属性的命名约定有一些隐藏的“陷阱”:

HTML:HTML:
<a id="bar" data-foo-bar-baz="fizz-buzz" href="#">fizz buzz!</a>
JS:JS:
console.log( $('#bar').data('fooBarBaz') );
//outputs "fizz-buzz" as hyphens are automatically camelCase'd

The hyphenated key will still work:

带连字符的键仍然有效:

HTML:HTML:
<a id="bar" data-foo-bar-baz="fizz-buzz" href="#">fizz buzz!</a>
JS:JS:
console.log( $('#bar').data('foo-bar-baz') );
//still outputs "fizz-buzz"

However the object returned by .data()will not have the hyphenated key set:

但是,返回的对象.data()不会设置带连字符的键:

$('#bar').data().fooBarBaz; //works
$('#bar').data()['fooBarBaz']; //works
$('#bar').data()['foo-bar-baz']; //does not work

It's for this reason I suggest avoiding the hyphenated key in javascript.

正是出于这个原因,我建议避免在 javascript 中使用带连字符的键。

For HTML, keep using the hyphenated form. HTML attributes are supposed to get ASCII-lowercased automatically, so <div data-foobar></div>, <DIV DATA-FOOBAR></DIV>, and <dIv DaTa-FoObAr></DiV>are supposedto be treated as identical, but for the best compatibility the lower case form should be preferred.

对于 HTML,请继续使用带连字符的形式。HTML属性应该得到ASCII-小写自动,所以<div data-foobar></div><DIV DATA-FOOBAR></DIV><dIv DaTa-FoObAr></DiV>认为被视为是相同的,但最好的相容性下壳体形式应是优选的。

The .data()method will also perform some basic auto-casting if the value matches a recognized pattern:

.data()如果值与识别的模式匹配,该方法还将执行一些基本的自动转换:

HTML:HTML:
<a id="foo"
    href="#"
    data-str="bar"
    data-bool="true"
    data-num="15"
    data-json='{"fizz":["buzz"]}'>foo!</a>
JS:JS:
$('#foo').data('str');  //`"bar"`
$('#foo').data('bool'); //`true`
$('#foo').data('num');  //`15`
$('#foo').data('json'); //`{fizz:['buzz']}`

This auto-casting ability is very convenient for instantiating widgets & plugins:

这种自动投射能力对于实例化小部件和插件非常方便:

$('.widget').each(function () {
    $(this).widget($(this).data());
    //-or-
    $(this).widget($(this).data('widget'));
});

If you absolutely must have the original value as a string, then you'll need to use .attr():

如果您绝对必须将原始值作为字符串,那么您需要使用.attr()

HTML:HTML:
<a id="foo" href="#" data-color="ABC123"></a>
<a id="bar" href="#" data-color="654321"></a>
JS:JS:
$('#foo').data('color').length; //6
$('#bar').data('color').length; //undefined, length isn't a property of numbers

$('#foo').attr('data-color').length; //6
$('#bar').attr('data-color').length; //6

This was a contrived example. For storing color values, I used to use numeric hex notation (i.e. 0xABC123), but it's worth noting that hex was parsed incorrectly in jQuery versions before 1.7.2, and is no longer parsed into a Numberas of jQuery 1.8 rc 1.

这是一个人为的例子。为了存储颜色值,我曾经使用数字十六进制表示法(即 0xABC123),但值得注意的是,十六进制在 1.7.2 之前的 jQuery 版本中被错误解析,并且不再被解析为NumberjQuery 1.8 rc 1。

jQuery 1.8 rc 1 changed the behavior of auto-casting. Before, any format that was a valid representation of a Numberwould be cast to Number. Now, values that are numeric are only auto-cast if their representation stays the same. This is best illustrated with an example.

jQuery 1.8 rc 1 改变了 auto-casting 的行为。以前,任何有效表示 a 的格式都Number将被强制转换为Number. 现在,数字值只有在它们的表示保持不变时才会自动转换。这最好用一个例子来说明。

HTML:HTML:
<a id="foo"
    href="#"
    data-int="1000"
    data-decimal="1000.00"
    data-scientific="1e3"
    data-hex="0x03e8">foo!</a>
JS:JS:
                              // pre 1.8    post 1.8
$('#foo').data('int');        //    1000        1000
$('#foo').data('decimal');    //    1000   "1000.00"
$('#foo').data('scientific'); //    1000       "1e3"
$('#foo').data('hex');        //    1000     "0x03e8"

If you plan on using alternative numeric syntaxes to access numeric values, be sure to cast the value to a Numberfirst, such as with a unary +operator.

如果您计划使用替代的数字语法来访问数字值,请确保将值强制转换为Number第一个,例如使用一元运算+符。

JS (cont.):JS(续):
+$('#foo').data('hex'); // 1000

回答by Travis J

The main difference between the two is where it is stored and how it is accessed.

两者之间的主要区别在于它的存储位置和访问方式。

$.fn.attrstores the information directly on the element in attributes which are publicly visible upon inspection, and also which are available from the element's native API.

$.fn.attr将信息直接存储在元素上的属性中,这些属性在检查时公开可见,也可从元素的本机 API 获得。

$.fn.datastores the information in a ridiculously obscureplace. It is located in a closed over local variable called data_userwhich is an instance of a locally defined function Data. This variable is not accessible from outside of jQuery directly.

$.fn.data将信息存储在一个可笑的晦涩的地方。它位于一个称为封闭的局部变量中data_user,该变量是本地定义的函数 Data 的一个实例。这个变量不能直接从 jQuery 外部访问。

Data set with attr()

数据集 attr()

  • accessible from $(element).attr('data-name')
  • accessible from element.getAttribute('data-name'),
  • if the value was in the form of data-namealso accessible from $(element).data(name)and element.dataset['name']and element.dataset.name
  • visible on the element upon inspection
  • cannot be objects
  • 可从 $(element).attr('data-name')
  • 可从element.getAttribute('data-name'),
  • 如果值的形式data-name也可以从$(element).data(name)element.dataset['name']element.dataset.name
  • 检查时在元素上可见
  • 不能是对象

Data set with .data()

数据集 .data()

  • accessible onlyfrom .data(name)
  • not accessible from .attr()or anywhere else
  • not publicly visible on the element upon inspection
  • can be objects
  • 访问.data(name)
  • 无法从.attr()其他任何地方访问
  • 检查时在元素上不公开可见
  • 可以是对象

回答by Yogendra Chauhan

You can use data-*attribute to embed custom data. The data-*attributes gives us the ability to embed custom data attributes on all HTML elements.

您可以使用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.data()方法允许您以一种安全的方式将任何类型的数据获取/设置到 DOM 元素,从而避免循环引用,从而避免内存泄漏。

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

jQuery.attr()方法仅获取/设置匹配集中第一个元素的属性值。

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");