2010-05-03 80 views
1

我處理與jQuery的一個列表項點擊:如何判斷jQuery點擊發生在哪個元素上?

$("#some_list li").click(function(event) { 
    // magic happens here 
    } 

列表項的樣子:

<li><input type='checkbox'>Some text<span class='info'>(?)</span></li> 

我想有根據不同的行爲是否內用戶點擊(? )或列表中的其他任何地方。如何檢測用戶點擊了哪個元素?

回答

5

this

$(this) 

所有事件處理程序中的元素的上下文中運行,所以this將參照本地DOM對象觸發事件的元素。

但是,這並不完全回答你的問題 - this將是處理程序註冊的元素。

要找到被點擊的實際元素(可以是this孩子),你應該寫$(e.target)

+1

+1,你應該只是澄清究竟在哪裏。 – 2010-05-03 00:58:24

0

我寫了一個簡單的jQuery代碼來獲取點擊的鏈接的數量。

var temp_str=''; 
$(document).ready(function(){ 
    $('a').click(function(e){e.preventDefault();}); 
    $(document).click(function(e){ 
     if($(e.target).data('count')==undefined) 
     $(e.target).data('count',0); 
      $(e.target).data('count',$(e.target).data('count')+1); 

    $('a').each(function(i,item){if($(item).data('count')!=undefined)temp_str+=$(item).html()+" : "+$(item).data('count')+"<br>";}); 
    $('#helper').html(temp_str); 
    temp_str=''; 
    }); 

    }); 
相關問題