2012-08-13 62 views
0

我無法理解一種jQuery選擇,我希望有人能以清晰的語言向我解釋。

它取自this Stack Overflow question

基本上,它有常見的jQuery:$(selector)

但它裏面有$({ y: iFrameScrollY })

我從來沒有見過這個。 括號內有{ ... }someVal: anotherVal是什麼意思?

此外,請爲這個問題推薦一個不同的標題,以使其他人更容易找到它。

+0

這將是與對象包裝的jQuery選擇器。 http://api.jquery.com/jQuery/ – 2012-08-13 09:30:08

+2

關於'{}'語法,這是一個JavaScript對象字面量(也稱爲對象初始化程序)。有關詳細信息,請閱讀[使用對象](https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Working_with_Objects)或其他有關對象的JS教程。如果你以前沒有見過,那麼當我根據[$()'函數文檔](http://api.jquery.com/jquery)的說法,它不會對你有意義/),當你將一個對象傳遞給'$()'時,它返回包裝在一個jQuery對象中的對象。 – nnnnnn 2012-08-13 09:30:33

+0

感謝Dan博士和nnnnnn,這真的很有幫助。我會閱讀這些文檔。 – shrewdbeans 2012-08-13 09:34:35

回答

3

什麼$({ y: iFrameScrollY })確實是環繞JavaScript對象{ y: iFrameScrollY }一個jQuery選擇對象。

JavaScript對象聲明爲{ y: iFrameScrollY },這意味着它包含一個名爲y的屬性,其值設置爲iFrameScrollY的值。

通過將對象封裝到jQuery對象中,可以對包裝對象執行jQuery方法。

有關更多詳細信息,請參閱此documentation

1

這是對jQuery()函數的調用,根據傳遞的參數,它被重載以執行許多不同的操作。

{someVal : anotherVal}是一個JavaScript對象,其屬性名爲someVal,其值等於anotherVal變量的值。

如果你加入這兩個信息拼在一起,並期待在鏈接頁面,你會看到這一點:

的jQuery(對象)

對象的普通對象在一個jQuery包目的。

3

包裝普通的JavaScript對象內jQuery對象,你可以使用一些jQuery方法包括:(),.trigger()和.triggerHandler。數據(),.道具(),. bind()的,.unbind() 。

下面是從jQuery.com截取的示例:

// define a plain object 
var foo = {foo:'bar', hello:'world'}; 

// wrap this with jQuery 
var $foo = $(foo); 

// test accessing property values 
var test1 = $foo.prop('foo'); // bar 

// test setting property values 
$foo.prop('foo', 'foobar'); 
var test2 = $foo.prop('foo'); // foobar 

// test using .data() as summarized above 
$foo.data('keyName', 'someValue'); 
console.log($foo); // will now contain a jQuery{randomNumber} property 

// test binding an event name and triggering 
$foo.bind('eventName', function(){ 
     console.log('eventName was called'); 
}); 

$foo.trigger('eventName'); // logs 'eventName was called'