2012-06-30 20 views
1

有道假設我有一個.on()函數其中i選擇多個ID是存在於多個選擇器迭代中的jquery

$("#i, #am, #your, #father").on("click" , function(event){ 
    //iterate over the selectors and return tagname 
     alert ($("#i").prop("tagName") ); 
     alert ($("#am").prop("tagName")); 
     alert ($("#your").prop("tagName")); 
     alert ($("#father").prop("tagName")); 
    } 

,我可以想到的是分別提醒每一個的唯一方法。有沒有一種已知的方法將$("#i, #am, #your, #father")作爲一種數組來處理?

+0

不會'警報($(本).prop( 「變量名」));'應該做要緊? –

回答

2

像這樣的事情?

var $groupSelection = $('#i, #am, #your, #father'); 

$groupSelection.on('click', function(e){ 
    $groupSelection.each(function(){ 
     alert($(this).prop('tagName')); 
    }); 
}); 

演示在http://jsfiddle.net/ZHpFa/

3

試試這個請:

有趣的閱讀:jQuery: What's the difference between '$(this)' and 'this'?

而且對任何這些鏈接ids可以使用$(this)獲得的點擊支撐tagName

另外,如果你想知道如何綁定所有他們對var看到這裏:$foo例如:http://jsfiddle.net/6hwLS/5/

希望這會有所幫助,

$("#i, #am, #your, #father").on("click" , function(event){ 
//iterate over the selectors and return tagname 
    alert($(this).prop("tagName") ); 

} 

進一步你也可以做到這一點

var $foo = $("#i, #am, #your, #father"); 

$foo.on("click", function(event) { 
    //iterate over the selectors and return tagname 
    alert($(this).prop("tagName")); 

}​ 
+0

最高評價評論說'基本上每次你得到一組元素後面jQuery把它變成一個數組'。這是否意味着通過調用'.on()',它不僅設置事件,而且還返回我的選擇器中的元素? – user571099

+1

嗨@ user571099酷,我估計理解'.on' PLZ在這裏閱讀:) http://api.jquery.com/on/ –

+0

啊謝謝。 '返回jquery'明白了:) – user571099