2009-09-29 22 views
2

Newb question:從jQuery選擇中返回單個對象而不是數組的最佳方式是什麼?

jQuery('。foo')[0]大部分時間都在做這項工作。 jQuery('。foo:first')[0]稍微更加明確和高效。 但是當數組爲空時,這並不好,因此檢查是必要的。

但是有沒有比使用數組索引器更好的方法?即返回是單個對象,或者如果未找到,則返回null。

我知道這是設計一個數組總是返回,因爲jQuery的力量在於「設置」操作。但有時更簡潔的語法確實有助於可讀性和避免錯誤。

+0

這是幾天前發佈的...... – 2009-09-29 14:18:21

+0

當數組爲空時,[0]將返回'undefined'..是否重要的​​是你得到'null'而不是? – 2009-09-29 15:10:18

+0

BTW undefined == null(altho undefined!== null) – 2009-09-29 15:11:28

回答

3

我給你做這個插件,希望這是有用的:

//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是最好的名字吧,有什麼建議麼?我也認爲singlefirst,但似乎無法彌補我的想法。

+0

+1,很好。也許'firstResult'? (雖然'getFirst'似乎有很多描述性。) – 2009-09-29 15:19:03

+0

我喜歡這一款。我認爲「第一」是一個合適的名字。 Single可能意味着結果中應該只有單個元素,如.Net Single()擴展方法。 – Xerion 2009-09-29 15:25:48

+0

我很驚訝,因爲jQuery經常使用,所以沒有將它作爲本機API。它有很多其他很好的語法糖,使JavaScript令人愉快... – Xerion 2009-09-29 15:27:06

1

如果我的選擇器不能保證返回至少一個元素,我傾向於使用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; 
}; 
0

你一定需要一個擴展這樣的事情:

$(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!"); 

你去那裏,沒有更多的數組下標!

相關問題