当前位置: 动力学知识库 > 问答 > 编程问答 >

jQuery select only the current element when using on click

问题描述:

Is it possible to cleanly select only the current clicked div and not children when using .on("click",?

Basically I have a outer div that when faded in is 100% width and 100% height, it then has a container in the middle, my aim is to have it when you click the outer div it fades both out but not when you click on the inner div.

I've created a jFiddle here to demonstrate the issue: http://jsfiddle.net/silver89/kaxsL/

I've tried using div > #box but had no luck so looking for more suggestions?

网友答案:

Try this:

$(document).on("click", "a", function(){
     $("#box").fadeIn("fast");
     return false;
});

$('div#box').on('click',function(e){
    $(this).fadeOut();
});

$('div.inner').on('click',function(e){
   e.stopPropagation();
});

You just need to stop the event from bubbling up. You can do whatever you want to select either div. ​

网友答案:

You can check the target. If the target is your #box then you can call fadeOut

$(document).on("click", "div > #box", function(e) {
    if (e.target.id === "box") {
        $("#box").fadeOut("fast");
    }
});​

Updated fiddle

网友答案:

DEMO on JsFiddle

$(document).on("click", "#box", function(){
      $("#box").fadeOut("fast");
});

$(document).on("click", "#box .inner", function(e){
   e.stopPropagation();
});​
网友答案:

Have you considered making the inner div independent of (e.g. not a child of) the outer div and use CSS to position the 'inner' box where you want it?

网友答案:

The event.target is the element that received the event. If it's not this, it's bubbling from a descendent.

$(document).on("click", "div > #box", function(ev){
    if( this == ev.target )
        $("#box").fadeOut("fast");
});

JSFiddle

分享给朋友:
您可能感兴趣的文章:
随机阅读: