[英]JavaScript trigger button by clicking another button
How can we use JavaScript to trigger more than one button?我们如何使用 JavaScript 触发多个按钮? I have 4 buttons.我有 4 个按钮。 When button 1 is press I want it to auto press button 2 3 and 4 but it should wait 1 second between each press.当按下按钮 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>
You cannot wrap buttons in script tags.您不能将按钮包装在脚本标签中。 Perhaps you meant也许你的意思是
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.