最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery: Click on *only* this element - Stack Overflow

programmeradmin1浏览0评论

In the highly-artistic drawing above, the green square is a child of the pink one. The pink one is wrapped around the green one by my function, so the green square could be anything - a hyperlink, an image, button, etc.

I want to capture a click on the pink div ONLY if it isn't a click on the green element too.

This could be done by flipping a Boolean using mouseenter on the green square, but that seems a messy way to do it to me.

Any clues?

IMPORTANT EDIT: I can't mess with the green square at all, so no adding anything to the click event.

In the highly-artistic drawing above, the green square is a child of the pink one. The pink one is wrapped around the green one by my function, so the green square could be anything - a hyperlink, an image, button, etc.

I want to capture a click on the pink div ONLY if it isn't a click on the green element too.

This could be done by flipping a Boolean using mouseenter on the green square, but that seems a messy way to do it to me.

Any clues?

IMPORTANT EDIT: I can't mess with the green square at all, so no adding anything to the click event.

Share Improve this question edited Sep 14, 2011 at 14:54 Grim... asked Sep 14, 2011 at 14:46 Grim...Grim... 17k7 gold badges46 silver badges61 bronze badges 3
  • 3 I am most upset that SO wouldn't let me create the new tag 'exciting image' =[ – Grim... Commented Sep 14, 2011 at 14:47
  • does this thread: stackoverflow.com/questions/6635659/… is about the same issue as yours? – JMax Commented Sep 14, 2011 at 14:50
  • Six months later and now I can create my own tags - not sure I will, though =] – Grim... Commented Feb 15, 2012 at 11:09
Add a comment  | 

5 Answers 5

Reset to default 9

You can do this:

$('.pink-box-selector').click(function(e) {
    if ($(e.target).is('.pink-box-selector')) {
        // do stuff here
    }
});

Two options. You can first either check if the target is the green div.

$('#pinkdiv').click(function(e) {
  if ($(e.target).is('#greendiv')) return;
  // handle the event
});

Or you can write the click handler for the pink div normally and stop clicks on the green div from propagating.

$('#greendiv').click(function(e) {
  e.stopPropagation();
});

Would $("#div_id :not('#excluded_element')).click(); help? http://api.jquery.com/not-selector/

Setup a separate click event listener for the "green" element and have it event.preventDefault()

http://jsfiddle.net/rlemon/d8qVp/

$("#pink").click(function(){
    if(!$("#green").is(":hover")) {
        alert('here');   
    }
});
发布评论

评论列表(0)

  1. 暂无评论