只有当JavaScript / jQuery中没有默认值时,该怎么做? [英] How to do an action only when there is no default in Javascript / jQuery?

查看:112
本文介绍了只有当JavaScript / jQuery中没有默认值时,该怎么做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被要求在div中的任何位置进行特定操作(比如说折叠),除非点击链接,按钮等...



基本上,我想反过来 event.preventDefault()



有没有一个很好的方法来做到这一点?



我正在寻找一个通用的解决方案;我不想太多关于div的内容。



可能看起来像:

 < div id =click_me> 
< p>点击这里应该做的东西
< a href =http://stackoverflow.com>但不这里,也不在下面的图像< / a>
< a href =/ xyz>< img url =/ icon.png/>< / a>
想象按钮...输入区域...
< / p>
< / div>

使用以下Javascript:

  $(#click_me)点击(function() 
if(black_magic){
$(#click_me)。toggleClass(collapsed);
}
});


解决方案

你只需要确保事件 target 不是链接,也不是按钮。

  $('#click_me')点击(function(e){
interactive ='a,button,input,textarea,video,map,object';
if($(event.target).closest(interactive).le ngth == 0)){
$(#click_me)。toggleClass(collapsed);
}
});


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");
  }
});

解决方案

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");
  }
});

这篇关于只有当JavaScript / jQuery中没有默认值时,该怎么做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆