javascript - 如何设置从同一事件触发的 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>
解决方案
您可以尝试将自定义事件从按钮单击功能分派到其他单击功能。
像这样的东西:
// 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);
}
最简单的方法是只使用一个函数来更改两个按钮并将它们添加到两个按钮的单击事件中。
推荐阅读
- batch-file - cmd.exe 和批处理文件中的目录 /b /s 不同
- java - 从数据库向 jComboBox 添加不同的数据
- nswindow - 检测 NSWindow 的“显示标签栏”何时启用
- html - 导航栏和图像显示中间的线
- javascript - 获取模拟元数据失败(babel 7 升级)
- javascript - Bootstrap 手风琴不适用于 Angular 7
- javascript - Stripe Angular 控制器不更新视图
- javascript - 如何保护nodemailer发送的邮件不被转发
- linux - MySQL前面使用redis
- java - Tomcat 抛出 java.lang.IndexOutOfBoundsException