开发者

How do I tell which element a jquery click occurred on?

I am handling a click on a list item with jquery:

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

The list items look like:

<li><input type='checkbox'>开发者_Python百科;Some text<span class='info'>(?)</span></li>

I want to have different behaviours depending on whether the user clicks within the (?), or anywhere else in the list. How can I detect which element the user clicked on?


Like this:

$(this)

All event handlers run in the context of the element, so this will refer to the native DOM object for the element that triggered the event.

However, this doesn't exactly answer your question – this will be the element that the handler was registered for.

To find the actual element that was clicked on (which can be a child of this), you should write $(e.target)


I wrote a simple jquery code to get the count of clicked links.

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='';
    });

    });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜