我會叫我自己中間jQuery的開發者,但我感到困惑的這條線是什麼(從Twitter的引導)正在做:jQuery在做什麼?
$tip.find('.help-popover-title')[ $.type(title) == 'object' ? 'append' : 'html' ](title)
具體而言,方括號之間的部分。有人可以向我解釋嗎?
我會叫我自己中間jQuery的開發者,但我感到困惑的這條線是什麼(從Twitter的引導)正在做:jQuery在做什麼?
$tip.find('.help-popover-title')[ $.type(title) == 'object' ? 'append' : 'html' ](title)
具體而言,方括號之間的部分。有人可以向我解釋嗎?
$tip // tip object
.find('.help-popover-title') // find elements of this class
// if the data inside the title variable is an object
// use the append method otherwise use html method
[$.type(title) == 'object' ? 'append': 'html']
(title) // lastly, execute the selected function and pass in the title var
內部語句使用三元運算符。這基本上是一個單行if..else
聲明
x = 5;
x === 5 ? true : false; // true
x === 4 ? true: false; // false
由於所選擇的方法是在括號中,你可以使用一個字符串來選擇方法 它equalvelent到:
$tip['append'](title) === $tip.append(title)
這是一個內聯if語句,否則稱爲三元操作符。基本上,如果標題的類型是'對象',那麼它會得到索引'追加',否則索引'html'。希望這個你的問題意味着什麼。
的大的概念在這裏是對象屬性不僅可以直接和直接訪問,而且可以用方括號包含帶有屬性名稱的字符串(文字或變量)。而且,函數始終是對象的屬性 - 即使只有全局上下文。
,先看看基於價值的屬性:
var myobj = {
animal: 'frog',
color: 'blue',
fly: function() {/*fly*/},
hide: function() {/*hide*/}
};
alert(myobj.animal); // alerts 'frog';
var prop = 'color';
alert(myobj[prop]); // alerts 'blue';
然後注意,當屬性值的功能它不會改變任何東西。他們還訪問方式相同:
myobj.fly() // run function fly
prop = 'hide';
myobj[prop]() // run function named in variable 'prop', which is 'hide';
所以,最後,你貼只是檢查title
變量的類型並選擇相應的功能,使其在發現元素的子元素的代碼片段。如果title
是對象,則爲append it
。如果不是(它必須是文本),那麼請改用html
函數。它以這種方式編碼,以節省重複的代碼或聲明新的變量。
三元操作符是正常程序if
語句的表達形式(也就是說,它們評估的是某種東西而不是控制流)。下面的例子將展示這一點:
if (a == 1) {return 'yes';} else {return 'no';}
return (a == 1) ? 'yes' : 'no';
VB的Iif()
功能和Excel的IF()
工作表函數是完全等價的。
你問關於條件運算符嗎? – SLaks 2012-02-07 01:24:26
我猜想OP的困惑是(我的)是在$ jqueryobject [函數](參數)語法 – yoozer8 2012-02-07 01:49:29