我们如何使用JavaScript触发多个按钮? 我有4个按钮。当按下按钮1时,我希望它自动按下按钮2 3和4,但是每次按下之间应等待1秒。
<script>
<button id="2" onclick="myFunction()">Click me</button>
<button id="3" onclick="myFunction()">Click me</button>
<button id="4" onclick="myFunction()">Click me</button>
</script>
<body><button id="1" onclick="myFunction(buttons)">Click me</button> </body>
答案 0 :(得分:1)
您不能将按钮包装在脚本标签中。 也许你是说
const buts = [];
let cnt = 0;
const clickThem = () => {
if (cnt >= buts.length) return;
buts[cnt].click();
setTimeout(clickThem,1000);
cnt++
}
window.addEventListener("load", function() {
document.getElementById("buttons").addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.classList.contains("autoclicked")) { // any of the auto clicked button
console.log("Button id", tgt.id); // or call a function
}
})
document.getElementById("button1").addEventListener("click",function() {
for (let sibling of this.parentNode.children) { // or document.querySelectorAll(".autoclicked")
if (sibling !== this) buts.push(sibling);
}
clickThem();
})
})
<div id="buttons">
<button id="button1">Click me</button>
<button class="autoclicked" id="button2">Click me</button>
<button class="autoclicked" id="button3">Click me</button>
<button class="autoclicked" id="button4">Click me</button>
</div>