How to do an action only when there is no default in Javascript / jQuery?

徘徊边缘 提交于 2019-12-14 01:19:18

问题


I'm asked that a click anywhere in a div does a specific action (say collapse it) unless the click was on a link, a button, etc...

Basically, I'd like the reverse of event.preventDefault().

Is there a good and easy way to do this?

I'm looking for a generic solution here; I would like to not assume much about the content of the div.

Might look like:

<div id="click_me>
<p>Clicking here should do stuff
   <a href="http://stackoverflow.com">but not here, nor on the following image</a>
   <a href="/xyz"><img url="/icon.png"/></a>
   imagine buttons... input areas, ...
</p>
</div>

With the following Javascript:

$("#click_me").click(function(){
  if(black_magic) {
    $("#click_me").toggleClass("collapsed");
  }
});

回答1:


You just have to make sure the event target is not a link nor a button.

$('#click_me').click(function(e) {
  interactive = 'a, button, input, textarea, video, map, object';
  if($(event.target).closest(interactive).length == 0) ) {
    $("#click_me").toggleClass("collapsed");
  }
});



回答2:


Just add this handler to your link:

$("#click_me a,button,input,textarea,video,map,object").click(function(e){
   e.stopPropagation();
});

To prevent the event to get to the div (bubble up). It will stop so the link will behave correctly.

See it in action. (click preview)




回答3:


Event bubbling is the keyword here. Bind an event handler to the div and check the event target to specify what to do.

$('div.mydivclass').bind('click', function(event){
    switch(event.target.id){
        case 'id_of_an_anchor':{
              alert('anchor was clicked');
              break;
        }
        case 'id_of_a_span':{
              alert('span was clicked');
              break;
        }
        default: {
              alert('something else was clicked within me');
        }
    }
});

Of course you can even check for the targets tagName or nodeType.




回答4:


function onClick(e){
    var gates = "A,INPUT,TEXTAREA,SELECT";
    var bound = this;
    var isCollapse = function ( node ){ 
    if( node == bound ){ return true; }
        var re = new RegExp( "\\b" +node.nodeName+ "\\b", "g" );
        return re.test( gates ) ? false : isCollapse( node.parentNode );
    };

    if( isCollapse( event.srcElement || e.target ) ){
        alert( "collapse" )
        // collapse()
    }
}
document.getElementById("click_me").onclick = onClick;

*fixed * for cases like: <a href="_"><span><strike> a link </strike></span></a>



来源:https://stackoverflow.com/questions/3152075/how-to-do-an-action-only-when-there-is-no-default-in-javascript-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!