简体   繁体   中英

Cannot trigger jQuery .click() for button that contains certain text?

I have a button:

 $('.add_to_cart span:contains("Choose a Size")').click(function() { console.log("it has been clicked") });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button type="submit" name="add" id="add-to-cart" class="action_button add_to_cart v-center" data-variantcount="44" data-label="Add to Cart" disabled=""> <span class="text">Choose a Size</span> </button>

However, this is never printing anything when I click it? You can see in this image that it is finding these elements but not triggering when clicked.

Are you loading the script after the DOM has loaded? Try:

$(function() {
  $('.add_to_cart span:contains("Choose a Size")').click(function () {
    console.log("it has been clicked")
   });
});

Could you try this?

$(document).on('click','.add_to_cart span:contains("Choose a Size")', function(){
console.log("it has been clicked");
});

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