Exclude click event based on condition?

2019-03-25 06:10发布

I'm trying to set conditions on a jQuery event. I have an input element and a div. I want to detect a click anywhere on the page and to execute that method but only if the click is not on the input or div.

5条回答
我欲成王,谁敢阻挡
2楼-- · 2019-03-25 06:14

Basically assign a click handler to the body of the page, then test the target Element of the event to see if the id of that target element matches your div or your input.

$("body").click(function(evt) {
  var targetElementId = evt.target.id;

  if (!(targetElementId  == "yourDivID" || targetElementId == "yourinputId"))
  {
    // your event code here.
  }
});
查看更多
虎瘦雄心在
3楼-- · 2019-03-25 06:16

Example to exclude specific elements using a wildcard:

$("#mydiv li").click(function(e){

        var Target = new String(e.target.id);

        // prevent action when a element with id containing 'img_' is clicked
        if( !Target.match(/img_/ )) {
            // do something
        }

});
查看更多
姐就是有狂的资本
4楼-- · 2019-03-25 06:17

Something like this should work.

$('body').click(function(event){ // body click
    var $target = $(event.target); // click target
    if($target.is('#mydiv, #myinput')) { // click target is div or input
        $target.click(); // click div or input
    }
});
查看更多
叛逆
5楼-- · 2019-03-25 06:18

Use the jQuery click() or live() functions and then check the target of the click event using the jQuery is() function.

  1. bind click event on document
  2. if the target is not input or div continue

.

$(document.body).click(function(e) {
  if( !$(e.target).is("input, div") ) {
    console.log("Run function because image or div were not clicked!");
  }
});

Example webpage => http://mikegrace.s3.amazonaws.com/forums/stack-overflow/example-document-click-exclusion.html

Example firebug output after clicking around on example page

alt text

查看更多
冷血范
6楼-- · 2019-03-25 06:19
var input = $("#yourInput")[0];
var div = $("#yourDiv")[0];

$(document.body).click(function(e) {
   switch ( e.target ) {
       case input: case div: return;
   }
   yourMethod();
});
查看更多
登录 后发表回答