Plus/minus incrementator in Jquery, how to generalize?

前端 未结 4 1510
攒了一身酷
攒了一身酷 2021-01-24 11:52

I\'m using this code

-
   0
+
<         


        
4条回答
  •  时光说笑
    2021-01-24 12:26

    If you want to genericise your code, then best method would be to use a single class on both elements that affect the value, but add a data attribute which is the factor to adjust the amount to add/remove. You can then wrap the controls in a single containing div to make DOM traversal easier.

    By using this pattern you can have multiple instances of the control on the page, with all buttons governed by a single click handler. Try this:

    $('.value-amender').click(function() {
      var $el = $(this);
      $el.closest('.amender-container').find('.value').text(function(i, t) {
        return parseInt(t, 10) + (1 * $el.data('factor'));
      });
    });
    
    
    - 0 +
    - 0 +

提交回复
热议问题