Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

javascript - jQuery数据与Attr?(jQuery Data vs Attr?)

What is the difference in usage between $.data and $.attr when using data-someAttribute ?

(是什么在使用之间的差别$.data$.attr当使用data-someAttribute ?)

My understanding is that $.data is stored within jQuery's $.cache , not the DOM.

(我的理解是$.data存储在jQuery的$.cache ,而不是DOM中。)

Therefore, if I want to use $.cache for data storage, I should use $.data .

(因此,如果要使用$.cache进行数据存储,则应该使用$.data 。)

If I want to add HTML5 data-attributes, I should use $.attr("data-attribute", "myCoolValue") .

(如果要添加HTML5数据属性,则应使用$.attr("data-attribute", "myCoolValue") 。)

  ask by John B translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

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

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

However when you store data on a DOM node in jQuery using data, the variables are stored on the node object .

(但是,当您使用数据在jQuery中的DOM节点上存储数据时,变量将存储在node 对象上 。)

This is to accommodate complex objects and references as storing the data on the node element as an attribute will only accommodate string values.

(这是为了容纳复杂的对象和引用,因为将数据存储在节点元素上作为属性将仅容纳字符串值。)

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:)

console.log( $('#bar').data('fooBarBaz') );
//outputs "fizz-buzz" as hyphens are automatically camelCase'd
JS:

(JS:)

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

The hyphenated key will still work:

(连字符的键仍然可以使用:)

HTML:

(HTML:)

$('#bar').data().fooBarBaz; //works
$('#bar').data()['fooBarBaz']; //works
$('#bar').data()['foo-bar-baz']; //does not work
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()返回的对象将没有设置连字符键:)

<a id="foo"
    href="#"
    data-str="bar"
    data-bool="true"
    data-num="15"
    data-json='{"fizz":["buzz"]}'>foo!</a>

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

(因此,我建议避免在javascript中使用连字符键。)

For HTML, keep using the hyphenated form.

(对于HTML,请继续使用连字符形式。)

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

(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('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 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:)

                              // 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"
JS:

(JS:)

+$('#foo').data('hex'); // 1000

This was a contrived example.

(这是一个人为的例子。)

For storing color values, I used to use numeric hex notation (ie 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 Number as of jQuery 1.8 rc 1.

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

jQuery 1.8 rc 1 changed the behavior of auto-casting .

(jQuery 1.8 rc 1更改了自动广播的行为 。)

Before, any format that was a valid representation of a Number would be cast to Number .

(以前,任何有效表示Number格式都将转换为Number 。)

Now, values that are numeric are only auto-cast if their representation stays the same.

(现在,只有数值表示形式保持不变时,才会自动广播数值。)

This is best illustrated with an example.

(最好用一个例子来说明。)

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 Number first, such as with a unary + operator.

(如果计划使用其他数字语法访问数字值,请确保首先将值转换为Number ,例如使用一元+运算符。)

JS (cont.):

(JS(续):)

 +$('#foo').data('hex'); // 1000 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...