2009-07-27 56 views
30

點擊'uploadChoice'內的其中一個div時,如何確定哪個點擊?我能否以某種方式返回'eq'值?在jquery中,你如何找出被點擊元素的'eq'?

<div id=uploadChoice> 
    <div>Text</div> 
    <div>Image</div< 
    <div>Text & Image</div> 
</div> 



$("#uploadChoice div").click(function(){ 
    //insert code here! :) 
}); 

回答

59
$('#uploadChoice div').click(function(event) { 
    var index = $(this).index(); 
}); 
+1

頂級標記我的朋友! :) – Stephen 2009-07-27 15:18:54

+1

太簡單了。萬分感謝! – 2013-03-22 14:26:02

0

你可以得到div的內容與

$("#uploadChoice div").click(function(){ 
    var choice = $(this).html; 
} 

然後只是做一個switch語句或一些嵌套IFS。

個人而言,我會爲每個div添加一個ID,並檢查點擊元素的ID。

+0

我可以問爲什麼這是被拒絕?它肯定會照顧原始海報的要求。實際上,它提供了兩個選項來識別用戶點擊哪個選項。 此外,此解決方案允許用戶重新排列按鈕而無需更改任何代碼,因爲它使用按鈕的值(或ID)而不是它們的相對位置。 – idrumgood 2009-07-27 19:25:57

5

,不需要重複選擇一個更簡單的替代以下

$('#uploadChoice div').click(function(event) { 
    var index = $(this).prevAll().length; 
}); 
2

您可以添加選擇爲好,並通過「$(本)」作爲參數:

$(document).on('click', 'button.testbutton', function() { 
 
    
 
    var index = $('div.example > div.xyz').find('button.testbutton').index($(this)); 
 

 
});