简体   繁体   中英

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.

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. What is your HTML code?

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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