简体   繁体   English

当出现体内类时,请防止单击。\\

[英]Prevent .on click when class in body is present.\

I'm really confused by this. 我对此很困惑。 I'd like a click to only happen when a class in the body is present, and not when a different class is present. 我希望单击仅在存在体内的某个类别时发生,而不是在存在其他类别时发生。

When you click, I'm adding the class to the body, but in my code, jquery is still allowing the action to happen on click. 当您单击时,我会将类添加到主体,但是在我的代码中,jquery仍然允许在单击时进行操作。

CodePen: https://codepen.io/omarel/pen/LLbwyq CodePen: https ://codepen.io/omarel/pen/LLbwyq

HTML HTML

<html>
<body class="comp-mode-off">

  <div class="sharelink">click</div>
  <div class="togglecompmode">toggle comp mode</div>
</body>
</html>

JQUERY JQUERY

var sharelinkbtn =  $( ".comp-mode-off .sharelink" ); 

$( sharelinkbtn ).on( "click", function() {
     alert("hi"); //should only happen when .comp-mode-off exists. 
 }); 

$( '.togglecompmode' ).on( "click", function() {

   $('body').toggleClass( "comp-mode-off comp-mode-on"); //but when i remove it, it still happens

 }); 

You are binding on the element which is selected initially but updating body class doesn't make any change to the attached handler. 您正在绑定最初选择的元素,但是更新body class不会对附加的处理程序进行任何更改。 So use event delegation to fire only when class exists for the body. 因此,仅当主体存在类时才使用事件委托来触发。

// use the selector as second argument
$(document).on( "click", 'body.comp-mode-off .sharelink', function() {
   alert("hi"); 
}); 

 $(document).on("click", 'body.comp-mode-off .sharelink', function() { alert("hi"); }); $('.togglecompmode').on("click", function() { $('body').toggleClass("comp-mode-off comp-mode-on"); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body class="comp-mode-off"> <div class="sharelink">click</div> <div class="togglecompmode">toggle comp mode</div> </body> 


Or check within the handler that class exists for the body. 或在处理程序中检查主体是否存在类。

var sharelinkbtn =  $( ".comp-mode-off .sharelink" ); 

$( sharelinkbtn ).on( "click", function() {
   // check class exists or not 
   if($('body.comp-mode-off').length){
   // or use $('body').hasClass('comp-mode-off')

      alert("hi");
   }
}); 

 var sharelinkbtn = $(".comp-mode-off .sharelink"); $(sharelinkbtn).on("click", function() { // check class exists or not if ($('body.comp-mode-off').length) { // or use $('body').hasClass('comp-mode-off') alert("hi"); } }); $('.togglecompmode').on("click", function() { $('body').toggleClass("comp-mode-off comp-mode-on"); //but when i remove it, it still happens }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body class="comp-mode-off"> <div class="sharelink">click</div> <div class="togglecompmode">toggle comp mode</div> </body> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM