开发者

get target clicked div even if it inside other divs (Just the target div and one event for it)

how can i get target clicked element even if this element inside other elements with same type like (div)

i have 3 divs inside each others , when i declare click events for div and i clicked top div i got 3 click events for the parents too.

so i want just one click events for the target element i clicked and ignore the others

My Try

jQuery('div').click(function(e)开发者_Python百科 {
    var clicked = jQuery(e.target);
    // Ensure we're checking which list item is clicked,
    // other children should be allowed
    if(clicked.parents().length > 0) {
        // :first ensures we do not select higher level list items
        alert($(clicked).html());
return ;    
    }
else
{
    alert($(clicked).html());
}

});


Your could try adding e.stopPropagation() inside your click event handler. This will allow the event to trigger on whichever div was clicked, but stop the event from going any further up the dom.


Doing stopPropagation is one method. Rather nicer, I think, is to check if the current element is the same as the event target, which means you can still handle events with handlers higher up the tree:

jQuery('div').click(function(e) {
    if (this === e.target) {
        // we're handling on the clicked element
    }
}


You need to stop the click event propagating up the DOM tree.

http://api.jquery.com/event.stopPropagation/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜