【发布时间】:2013-02-10 06:07:47
【问题描述】:
这段代码最能说明我的困惑。
var nativeObj, jWrapped, jSelector;
//WIAT = "What I Am Thinking"
nativeObj = $( '#tableTab' ) [0]; //WIAT: unwrap the jQuery object created by the selector and get the native DOM object
jWrapped = $( nativeObj ); //WIAT: wrap up the native DOM object again... should be equal to $( '#tableTab' )
jSelector = $( '#tableTab' ); //WIAT: pass the jQuery object as reference to jSelector variable
// set the data with jQuery's .data method
$.data( jWrapped, 'key', { test: 12 } ); //WIAT: will be equivalant to using $( '#tableTab' ) and should attach the data to it
$.data( $( '#tableTab' ) [0], 'key', { test: 34 } ); //WIAT: using the native DOM obj, it shouldn't work with this, since it doesn't specify in the docs
$.data( $( '#tableTab' ) , 'key', { test: 56 } ); //WIAT: should rewrite the data in the element to { key: { test: 56} }
console.log( $.data ( jWrapped ) ); // {key:{test:12}}
console.log( $.data ( jWrapped[0] ) ); // {key:{test:34}}
console.log( $.data ( nativeObj ) ); // {key:{test:34}}
console.log( $.data ( $( nativeObj ), 'test' ) ); // undefined
console.log( $.data ( $( '#tableTab' ) [0] ) ); // {key:{test:34}}
console.log( $.data ( $( '#tableTab' ) , 'test' ) ); // undefined
哇,等等,发生了什么事?
1.为什么我得到不同的结果?我只使用了 1 个选择器并引用了一个元素。
2.为什么对象引用jWrapped 和来自$( '#tableTab' ) 的对象不产生相同的结果?
3.Furthermore jWrapped 和 jWrapped[0] 正在产生不同的结果? 前者是 jQuery 包装对象,后者是原生 DOM 对象。本质上,它们是引用相同的元素但结果不同!??
//Now let's see what's inside the objects
console.log( $( '#tableTab' ) [0]); // [object HTMLDivElement]
console.log( nativeObj ); // [object HTMLDivElement]
console.log( $( nativeObj ) ); // {0:({}), context:({}), length:1}
console.log( jWrapped ); // {0:({}), context:({}), length:1, jQuery182021025872972076787:{toJSON:(function () {}), data:{key:{test:12}}}}
console.log( $( '#tableTab' ) ); // {length:1, 0:({}), context:({}), selector:"#tableTab"}
console.log( jSelector ); // {length:1, 0:({}), context:({}), selector:"#tableTab"}
好的nativeObj == $( '#tableTab' ) [0]这就是我所期望的
哇,这很奇怪,为什么jWrapped == $( nativeObj ) 不呢?
很好,jSelector = $( '#tableTab' ) 这也是我所期望的
鉴于这些数据,我可以推断 $.data 必须接受本机 DOM 元素,但是
$( '#tableTab' ).data( 'key' , { test: 78 } );
console.log($( '#tableTab' ).data('key')); // 78
嗯,对不起,控制台先生......不是很酷的人。
好吧,我非常困惑和沮丧,我讨厌 jQuery,我讨厌 Javascript,我讨厌 IE... 好吧,不,我只是讨厌 IE,但那是另一回事了。为什么 jQuery 的行为如此奇怪?我觉得玩 IE 太多了...
我的猜测是它与 $.data 在 jQuery 中的工作方式有关,它实际上并不将数据附加到元素,而是 将数据存储在其自己的对象中,并基于解析传递给它的数据来引用数据。我发现错误了吗?
帮助。
我也确实看过How does jQuery .data() work?,虽然它确实提供了一些很好的信息,但它仍然没有回答这里发生的事情,这是我真正的问题。虽然它确实证实了我的想法,即没有数据存储在元素中,而是存储在 jQuery 对象中。
【问题讨论】:
标签: javascript jquery jquery-ui object