Loop

时间:2016-03-09 13:09:49

标签: php jquery

我目前有一个 - / +数量的功能设置并且正常工作,但是当将它添加到循环中时,单击 - / +按钮时数量大小与每个输入重复 - 请参阅附件。

Screenshot

任何帮助和建议都会有所帮助。

PHP

while ( $loop->have_posts() ) : $loop->the_post();
                $price = get_post_meta( get_the_ID(), '_regular_price', true);
                echo '<li id="'.$subID.'">'.get_the_title().' - £'.$price .' - ID '.$product->id.' ';
                echo '<form id="'.$product->id.'" method="POST" action="#">';
                echo '<input type="button" value="-" class="qtyminus" field="quantity" />';
                echo '<input type="text" name="quantity" value="0" class="qty" />';
                echo '<input type="button" value="+" class="qtyplus" field="quantity" />';
                echo '</form>';
                echo '</li>';
              endwhile;

JS

function qty() {
$('.qtyplus').click(function(e){
    e.preventDefault();
  var fieldName = $(this).attr('field');
  var currentVal = parseInt($('input[name='+fieldName+']').val());
  if (!isNaN(currentVal)) {
    $('input[name='+fieldName+']').val(currentVal + 1);
  } else {
    $('input[name='+fieldName+']').val(0);
  }
});
$(".qtyminus").click(function(e) {
    e.preventDefault();
  var fieldName = $(this).attr('field');
  var currentVal = parseInt($('input[name='+fieldName+']').val());
  if (!isNaN(currentVal) && currentVal > 0) {
    $('input[name='+fieldName+']').val(currentVal - 1);
  } else {
    $('input[name='+fieldName+']').val(0);
  }
});
}

2 个答案:

答案 0 :(得分:1)

您应该找到相同形式的元素

<强> JS

function qty() {
  $('.qtyplus').click(function(e){
      e.preventDefault();
      var fieldName = $(this).attr('field');

      // find the element in the same form of the button qtyplus:
      var element=$(this).closest('form').find('input[name='+fieldName+']');

      var currentVal = parseInt(element.val());
      if (!isNaN(currentVal)) {
        element.val(currentVal + 1);
      } else {
        element.val(0);
    }
  });
  $(".qtyminus").click(function(e) {
    e.preventDefault();
    var fieldName = $(this).attr('field');

    // find the element in the same form of the button qtyminus:
    var element=$(this).closest('form').find('input[name='+fieldName+']');

    var currentVal = parseInt(element.val());
    if (!isNaN(currentVal) && currentVal > 0) {
      element.val(currentVal - 1);
    } else {
      element.val(0);
    }
  });
}

答案 1 :(得分:0)

这种情况正在发生,因为您要定位页面上具有name="quantity"属性的所有输入。尝试更准确地指定要应用更改的输入。例如:

function clickResponse(event) {
    var parent = $(this).closest('form');
    var targetInput = parent.find('input[name="' + $(this).attr('field') + '"]');
    // your code
}
相关问题