简体   繁体   中英

Auto click div button with jquery

I can't get jquery to programatically click this button:

<div class="cta bt-add-to-cart" data-prid="90859" role="button" data-error="Per procedere devi selezionare la taglia!">
    <div>Aggiungi al carrello</div>
</div>

I tried this:

$('.cta bt-add-to-cart').click();

or this:

$('.cta bt-add-to-cart').trigger('click');

Your jQuery selector does not select the button with the HTML you posted - it should be the following:

$('.cta.bt-add-to-cart').trigger('click');

This should select the element which has both cta and bt-add-to-cart classes, and trigger any on click events bound to it.

You have to specify what function to execute when the click takes place. Neither of your attempts do that.

Also, the JQuery selector needs no space between the class names otherwise it will be looking for elements that have the class bt-add-to-cart that are descendants of elements that have the class cta .

Here's an example:

 function theCallbackFunction(){ // This is where the code to execute lives alert("You clicked me!"); } // This sets up the function as the click event handler for the element $('.cta.bt-add-to-cart').on("click", theCallbackFunction); // And this is a way to simulate the user clicking the element $('.cta.bt-add-to-cart').trigger('click'); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="cta bt-add-to-cart" data-prid="90859" role="button" data-error="Per procedere devi selezionare la taglia!"> <div>Aggiungi al carrello</div> </div> 

试试这个$('.bt-add-to-cart').click()$('.cta bt-add-to-cart')返回一个像对象的空数组,如果您想将两个分类的类组合在一起,那么您可以这样做$('.cta.bt-add-to-cart')

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