简体   繁体   中英

How to create a unique id for each button on jQuery?

please advise how to improve this jQuery script:

jQuery(function($) {
  $('.qty').on('input change', function() { 
   $('#ajaxadd').attr( 'data-quantity', $( this ).val() ); });
});

This script adds the number of items to the "data-quantity" field:

<button id="ajaxadd" data-quantity="">Add to cart</button>

I need:

<button id="ajaxadd-2" data-quantity="">Add to cart</button>        
<button id="ajaxadd-3" data-quantity="">Add to cart</button>

The problem is that the script is executed only for the first item on the list. For other products does not work, I need a unique ID for each product.

you can use it



  function changeidofallbtn() {
    var allbtn = document.getElementsByTagName('button');
    //var all = document.getElementsByTagName("*");

    for (var i=0, max=allbtn.length; i < max; i++) {
       var btn_id = allbtn[i].id;     
      document.getElementById(btn_id).id = 'ajaxadd-'+i;
        
    }
  }

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