Colen
Colen

Reputation: 13908

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'>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?

Upvotes: 1

Views: 587

Answers (2)

user3774128
user3774128

Reputation: 1

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

    });

Upvotes: 0

SLaks
SLaks

Reputation: 887449

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)

Upvotes: 5

Related Questions