Newb question:從jQuery選擇中返回單個對象而不是數組的最佳方式是什麼?
jQuery('。foo')[0]大部分時間都在做這項工作。 jQuery('。foo:first')[0]稍微更加明確和高效。 但是當數組爲空時,這並不好,因此檢查是必要的。
但是有沒有比使用數組索引器更好的方法?即返回是單個對象,或者如果未找到,則返回null。
我知道這是設計一個數組總是返回,因爲jQuery的力量在於「設置」操作。但有時更簡潔的語法確實有助於可讀性和避免錯誤。
Newb question:從jQuery選擇中返回單個對象而不是數組的最佳方式是什麼?
jQuery('。foo')[0]大部分時間都在做這項工作。 jQuery('。foo:first')[0]稍微更加明確和高效。 但是當數組爲空時,這並不好,因此檢查是必要的。
但是有沒有比使用數組索引器更好的方法?即返回是單個對象,或者如果未找到,則返回null。
我知道這是設計一個數組總是返回,因爲jQuery的力量在於「設置」操作。但有時更簡潔的語法確實有助於可讀性和避免錯誤。
我給你做這個插件,希望這是有用的:
//return single DOM element or null
jQuery.fn.getFirst = function() {
var ele = jQuery(this).filter(':first')[0];
if(ele !== undefined) {
return ele;
}
return null;
};
簡單的測試案例:
<input name="foo" value="hooohooo" class="test"/>
<input name="bar" value="heeeeheeee" class="test"/>
jQuery(document).ready(function() {
alert(jQuery('.test').getFirst()); //alerts [object HTMLInputElement]
alert(jQuery('.nonExistent').getFirst()); //alerts 'null'
});
我不知道,如果getFirst
是最好的名字吧,有什麼建議麼?我也認爲single
和first
,但似乎無法彌補我的想法。
如果我的選擇器不能保證返回至少一個元素,我傾向於使用each()
迭代集合。
jQuery('.foo').each(function() {
this;
});
我甚至會這樣做,如果我是排位選擇器與類似:first
。
jQuery('.foo:first').each(function() {
this;
});
編輯:我看到實現 「getFirst」 方法其他的答案。雖然我看不到它的用處,但我承認這一點。它具有相同的功能,但我認爲one
是一個更合適的名稱 - 避免與:first
選擇器混淆。我會很樂意看到這個用例。
/**
* Return the first item of the collection, or
* null if the collection is empty.
*/
jQuery.fn.one = function() {
return this[0] || null;
};
你一定需要一個擴展這樣的事情:
$(document).ready(function() {
jQuery.fn.getFirst = function() {
if(this.length == 0)
return null;
else
return this.get(0);
}
var ret = 0;
ret = $(".foo").getFirst();
if(ret)
$(ret).text("Tight!");
你去那裏,沒有更多的數組下標!
這是幾天前發佈的...... – 2009-09-29 14:18:21
當數組爲空時,[0]將返回'undefined'..是否重要的是你得到'null'而不是? – 2009-09-29 15:10:18
BTW undefined == null(altho undefined!== null) – 2009-09-29 15:11:28