简体   繁体   English

单击 function 仅在第二次单击时起作用

[英]Click function only working on second click

I have a click function that finds hidden buttons with the same class name and clicks them all with one click of another, visible button.我点击 function 找到具有相同名称 class 的隐藏按钮,然后单击另一个可见按钮将它们全部单击。

The problem is that it's only running correctly on the second click.问题是它只有在第二次点击时才能正确运行。 On the first click, the it only triggers one hidden button click, not all...在第一次点击时,它只会触发一个隐藏按钮点击,而不是所有......

Here's my code:这是我的代码:

$(document).ready(function(){
$('.mybtn').click(function(){
   var $parent = $(this).closest('.box-half');
   $parent.find(".add-cart").trigger('click');
});
});

I've also tried this我也试过这个

function myFunction() {
    document.querySelectorAll('.add-cart').forEach(function(el) {
       el.click();
    });
}
document.querySelector('.mybtn').onclick = myFunction;

Any help is much appreciated!任何帮助深表感谢!

I tested this HTML with both of your scripts, and it worked for me.我用你们的两个脚本测试了这个 HTML,它对我有用。 What is your HTML code?您的 HTML 代码是多少?

<div class="box-half">
    <button class="mybtn">Click mybtn</button>
    <button class="add-cart" style="display:none" id="b1" onclick="console.log(this.id)"></button>
    <button class="add-cart" style="display:none" id="b2" onclick="console.log(this.id)"></button>
    <button class="add-cart" style="display:none" id="b3" onclick="console.log(this.id)"></button>
</div>

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

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