jQuery .data和.attr怪异行为? [英] jQuery .data and .attr weird behaviour?

查看:60
本文介绍了jQuery .data和.attr怪异行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能解释以下小提琴中奇怪的jquery行为吗?

Can anyone explain the weird jquery behaviour found in the following fiddle?

http://jsfiddle.net/HSyS6/2/

我有以下html ...

I have the following html...

<div id="test" data-prevy="0"></div>

使用以下jquery ...

With the following jquery...

console.log($('#test').data('prevy'));
console.log($('#test').attr('data-prevy'));

$('#test').attr('data-prevy', 2);

console.log($('#test').data('prevy'));
console.log($('#test').attr('data-prevy'));

$('#test').attr('data-prevy', 1);

console.log($('#test').data('prevy'));
console.log($('#test').attr('data-prevy'));

哪个输出...

0
0
0
2
0
1

我希望它能输出...

When I would expect it to output...

0
0
2
2
1
1

我意识到,如果您通过.data(IE:.data('prevy',2);)设置该值,则该值将不会反映在DOM中,但是我做相反的事情,并且得到了更多意外结果

I realize that if you set the value via .data (IE: .data('prevy', 2);) that the value will not reflect in the DOM, but I am doing the opposite and getting even more unexpected results.

推荐答案

.data()不会设置或更改元素的属性,它只是初始获取它的值,然后更新内部对象存储在jQuery中作为元素.

.data() does not set or change the attribute of the element, it just gets the value of it initially, then updates an internal object stored within jQuery for the element.

内部数据首次初始化后,它永远不会返回属性来获取或设置值,因此,如果您已经在属性上使用过.data,则更新属性不会更新.data()中存储的内容.元素.

After the internal data is first initialized, it never goes back to the attribute to get or set the value, therefore updating the attribute will not update what is stored in .data() if you've already used .data on that element.

由于您仅更新属性,因此内部存储的数据永远不会更新,而只会更新属性.这是预期的行为.

Since you are only updating the attribute, the internal stored data is never updated, only the attribute. This is the intended behavior.

作为参考, https://github.com/jquery /jquery/blob/1.9-stable/src/data.js

这篇关于jQuery .data和.attr怪异行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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