简体   繁体   English

jQuery点击事件定位到多个元素

[英]Jquery click event targeting more than one element

Codepen is here Codepen在这里

I have two triggers on an image. 我在图像上有两个触发器。 General behaviour: 一般行为:

  • When I click a trigger, it should reveal a small context box (got this working) 单击触发器时,它应该显示一个小的上下文框(完成此工作)
  • When I click outside of the context box OR the trigger, it should disappear (got this working) 当我在上下文框或触发器之外单击时,它应该消失(完成此工作)
  • When I click another trigger, if there is another trigger/context box that is already active/open, it should close the other one and open the recently click one (not working) 当我单击另一个触发器时,如果存在另一个已激活/打开的触发器/上下文框,则应关闭另一个触发器并打开最近单击的触发器(不起作用)

Here's the html: 这是html:

<span class='pulse-button' id="button-1"></span>

<div class="content-box context-closed tabs" id="tabs1">
</div>

Here's my jQuery: 这是我的jQuery:

$(function(){
  $(".pulse-button").click(function(e){
    e.stopPropagation();
    if( $(".pulse-button").not(this).hasClass("pulse-button-active")){
      $(".pulse-button").not(this).removeClass("pulse-button-active");
      $(".pulse-button").not(this).next().addClass("context-closed");
    }else{
      $(this).addClass("pulse-button-active");  
      $(this).next().removeClass("context-closed");
    };
  });

  $("body").click(function(evt){
    if(evt.target.class == "content-box")
      return;
    if($(evt.target).closest('.content-box').length)
          return;
    if( $(".pulse-button").hasClass("pulse-button-active")){
      $(".pulse-button").removeClass("pulse-button-active");
      $(".pulse-button").next().addClass("context-closed");
    };
  });

  $( "#tabs1,#tabs2" ).tabs();
});

What could I be doing wrong here? 我在这里可能做错了什么?

You don't need the else in your .pulse-button click. .pulse-button单击中不需要else Because the code in else block should be executed either any .pulse-button has class pulse-button-active or not. 因为应该执行else块中的代码,所以任何.pulse-button都必须具有pulse-button-active类。 Change the your click event like following. 如下更改您的点击事件。

$(".pulse-button").click(function(e){
    e.stopPropagation();
    if($(".pulse-button").not(this).hasClass("pulse-button-active")) {
        $(".pulse-button").not(this).removeClass("pulse-button-active");
        $(".pulse-button").not(this).next().addClass("context-closed");
    }
    $(this).addClass("pulse-button-active");  
    $(this).next().removeClass("context-closed");
});

UPDATED PEN 笔更新

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

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