首页 > 解决方案 > 如何设置从同一事件触发的 2 个按钮?

问题描述

问题在代码片段中。哪个是: 当 $("#b").click 事件发生时,它是否也可能改变按钮 A?按钮 A 和 B 在不同的功能/类中。当 $("#b").click 事件发生时,我应该如何将此事件从 wrapperB 传递给 wrapperA 以执行某些操作?

function wrapperA(){

  function init(){
    // if B button clicked.
    // change A button html text to "A" or "a" (action to do in actual is different from wrapperB)
  }

   return {
     init: init
   };
}

function wrapperB(){

   function init() {
    $("#b").click(function() {
     if($("#text").html() === "UpperCase"){
      $("#b").html("b");
     } else {
     $("#b").html("B");
     }
     
     $("#text").html(
       ($("#text").html() === "UpperCase") ?
       "LowerCase" :
       "UpperCase"
     );
    });

   }
   
   return {
     init: init
   };
}

// is it possible when $("#b").click event happen, it change button A too? Button A & B are in different function/class. How should I pass this event from wrapperB to wrapperA to do something too when $("#b").click event happened?
wrapperA().init();  
wrapperB().init();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="wrapperA">
<button id="a">A</button>
</div>

<div id="wrapperB">
<button id="b">B</button>
<div id="text">UpperCase</div>
</div>

标签: javascript

解决方案


您可以尝试将自定义事件从按钮单击功能分派到其他单击功能。

像这样的东西:

// wrapperA

function init() {
  buttonAction();
  window.addEventListener('onButtonB', buttonAction);
}

function buttonAction() {
  // do button action
  let buttonEvent = new CustomEvent('onButtonA');
  window.dispatchEvent(buttonEvent);
}

对于另一个按钮:

// wrapperB

function init() {
  buttonAction();
  window.addEventListener('onButtonA', buttonAction);
}

function buttonAction() {
  // do button action
  let buttonEvent = new CustomEvent('onButtonB');
  window.dispatchEvent(buttonEvent);
}

最简单的方法是只使用一个函数来更改两个按钮并将它们添加到两个按钮的单击事件中。


推荐阅读