【问题标题】:Using html:not when element has multiple classes使用 html:not 当元素有多个类时
【发布时间】:2017-01-04 12:08:51
【问题描述】:

我有一个包含多个类名的元素,我不能为这个元素使用 ID。我想在单击元素或单击其他任何内容时触发单独的事件。现在,当我单击元素时,由于多个类名而触发了单击其他任何内容的事件。我该如何解决这个问题?我打算使用 JQuery。

<!DOCTYPE html>
<html lang="en-US">
<head>
    <title></title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
</head>
<body>
    <h1></h1>
    <div class="stack a b c">
        1
    </div>
    <div class="stack a b c">
        2
    </div>    
<script src="js/jquery-1.9.1.js"></script>      
<script>        
$('.a').click(function() {
  console.log("stack clicked");
});

$("html:not(.stack, .a, .b, .c)").click(function() {
  console.log("other clicked");
});

</script>    
<style>    
    .stack{
        width:100px;
        height:100px;
        background-color:red;
        border:1px solid black;    
    }    
</style>
</body>
</html>

【问题讨论】:

  • 你想达到什么目的?
  • 您在寻找$("html:not(.stack.a.b.c)")吗?
  • event.stopPropagation()
  • @Naila 我的最终目标是在单击按钮时出现下拉菜单,并在单击其他任何位置时使其消失

标签: javascript jquery html css


【解决方案1】:
  • 排除包含任何这些类的html元素

使用 CSS 选择器:

$("html:not(.stack),html:not(.a),html:not(.b),html:not(.c)").click(function() {
  console.log("other clicked");
});

或者使用 jQuery:

$("html").not(".stack, .a, .b, .c").click(function() {
  console.log("other clicked");
});

  • 排除包含所有这些类的html元素

使用 CSS 选择器,这个不好的地方是你必须按每个顺序尝试所有类的组合,所以最好使用 jQuery:

$('html:not([class="stack a b c"])').click(function() {
  console.log("other clicked");
});

或者使用 jQuery:

$("html").not(".stack.a.b.c").click(function() {
  console.log("other clicked");
});

【讨论】:

  • 这不起作用单击堆栈仍会触发 console.log("other clicked");
【解决方案2】:

html:not(... 将选择不包含任何这些类的 html 标记。要监听任何内部元素,只需使用 :not() 伪类。虽然使用event.stopPropagation 来防止事件冒泡到DOM 树。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h1>H</h1>
<div class="stack a b c">
  1
</div>
<div class="stack a b c">
  2
</div>


<script>
  $('.a').click(function(e) {
    e.stopPropagation();
    console.log("stack clicked");
  });

  $(":not(.stack.a.b.c)").click(function(e) {
    e.stopPropagation();
    console.log("other clicked");
  });
</script>

<style>

【讨论】:

  • 您的 sn-p 在单击堆栈时仍会触发“其他单击”
  • @user2557850 :很高兴为您提供帮助 :)
【解决方案3】:

这是我根据答案使用的。

$('.a').click(function(e) {
    e.stopPropagation();
  console.log("stack clicked");
});

$('html').click(function(e) {
    console.log("other clicked");
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-15
    • 2022-01-21
    • 1970-01-01
    • 2014-03-08
    • 2013-02-07
    • 2015-01-11
    • 1970-01-01
    相关资源
    最近更新 更多