简体   繁体   中英

Execute jQuery.click on a selector that contains multiple elements

I have 2 identic buttons with the id of "data-side-remove":
I also have the following jQuery function

  $('#data-side-remove').click(function(){ $(this).closest('.line-item-info').slideUp("slow"); window.location.href = $(this).attr("data-href-remove"); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="data-side-remove" class="plus-box" data-href-remove="/cart/change?line={{ forloop.index }}&amp;quantity=0" type="button" name="button">x</button> 

but for some reason, the code is working fine just for the first of the two button. Then, once its disappeared thanks to the the slideUp function, the code is working also for the second button, and so on. I guess it's something related to the fact that once its selected, $('#data-side-remove') becomes an array, and the function is just working on the first element of the array. What is the best way to get around this?

The $(this) will pull the href for the unique plus-box you clicked

  $('.plus-box').click(function(){ $(this).closest('.line-item-info').slideUp("slow"); window.location.href = $(this).attr("data-href-remove"); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="data-side-remove" class="plus-box" data-href-remove="/cart/change?line={{ forloop.index }}&amp;quantity=0" type="button" name="button">x</button> 

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