有关于切换两个类的问题

时间:2017-12-22 18:30:54

标签: javascript jquery

您能否请一看这个演示,让我知道为什么我无法在此代码段中使用var Phase; $(".btn-default").on("click", function(){ $(this).find('.glyphicon').toggleClass("glyphicon-remove glyphicon-ok"); });

label.btn {
    margin-bottom: 0;
    padding: 0;
    overflow: hidden;
}
    span {
      display: block;
      padding: 6px 12px;
    }

    input[type=checkbox] {
      display: none;
    }

    input:checked + span {
      display: block;
      color: #fff;
      background-color: #285e8e;
    }
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<div class="container">
<div class="btn-group">
    <label class="btn btn-default"><input name="phase" type="checkbox" value="A"><span><span class="glyphicon glyphicon-remove" aria-hidden="true"></span> A</span></label>
    <label class="btn btn-default"><input name="phase" type="checkbox" value="B"><span><span class="glyphicon glyphicon-remove" aria-hidden="true"></span> B</span></label>
    <label class="btn btn-default"><input name="phase" type="checkbox" value="C"><span><span class="glyphicon glyphicon-remove" aria-hidden="true"></span> C</span></label>
</div>
  </div>
tsconfig.json

1 个答案:

答案 0 :(得分:1)

这是因为synthetic*点击了input。事实上,click事件在标签级别被触发两次。

一种解决方案是按事件目标进行过滤:

&#13;
&#13;
var Phase;
$(".btn-default").on("click", function(e) {
  if (!$(e.target).is('input')) return;
  $(this).find('.glyphicon').toggleClass("glyphicon-remove glyphicon-ok");
});
&#13;
label.btn {
  margin-bottom: 0;
  padding: 0;
  overflow: hidden;
}

span {
  display: block;
  padding: 6px 12px;
}

input[type=checkbox] {
  display: none;
}

input:checked+span {
  display: block;
  color: #fff;
  background-color: #285e8e;
}


}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<div class="container">
  <div class="btn-group">
    <label class="btn btn-default"><input name="phase" type="checkbox" value="A"><span><span class="glyphicon glyphicon-remove" aria-hidden="true"></span> A</span></label>
    <label class="btn btn-default"><input name="phase" type="checkbox" value="B"><span><span class="glyphicon glyphicon-remove" aria-hidden="true"></span> B</span></label>
    <label class="btn btn-default"><input name="phase" type="checkbox" value="C"><span><span class="glyphicon glyphicon-remove" aria-hidden="true"></span> C</span></label>
  </div>
</div>
&#13;
&#13;
&#13;

*注意:Putting IP Address into bash variable. Is there a better way

  

当用户代理要运行合成点击激活步骤时   在元素中,用户代理必须运行预先单击激活步骤   element,然后在元素上触发click事件。默认操作   此单击事件必须是在运行后单击激活步骤   元件。如果事件被取消,则用户代理必须运行已取消   而是激活元素上的步骤。