使用jquery将值设置为属性

时间:2022-11-19 15:25:41

I want to add value to attribute. I found this one, but my requirments little different. I want to set value in function onclick="add('id', 5)".

我想为属性添加值。我找到了这个,但我的要求有点不同。我想在函数中设置值onclick =“add('id',5)”。

onclick="cart.add('<?php echo $product['product_id']; ?>', here i want to set with jQuery);"

Please also view my code

还请查看我的代码

1 个解决方案

#1


1  

A stronger solution:

更强的解决方案:

Set the data-productid to both the input and the test button:

将data-productid设置为输入和测试按钮:

var cart = { // JUST TO TEST
  add : function(productid, val){
    alert(productid +' '+ val);
  }
}

$(function () { // DOM ready

  $('.qtyplus, .qtyminus').on('click',function(){
    var $qty    = $('.featured-shopping-qty');
    var currVal = Math.abs( parseInt($qty.val(), 10) );
    var isPlus  = $(this).hasClass("qtyplus");
    var calc    = currVal + (isPlus? 1 : -1)
    $qty.val( (!isNaN(calc) && calc>=0) ? calc : 0);
  });
  
  $(document).on("click", ".throwToBasket", function(){
    var productid = $(this).attr("data-productid");
    var val  = parseInt( $("input[data-productid='"+ productid +"']").val() , 10);
    cart.add(productid, val);
  });
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="qtybox">
  <input type="text" name="quantity" value="0" class="qty featured-shopping-qty" data-productid="aaaaa">
</div>
<div class="plusminus">
  <div><input type="button" value="+" class="qtyplus"></div>
  <div><input type="button" value="-" class="qtyminus"></div>
</div>
<a href="javascript:void(0);" class="throwToBasket" data-productid="aaaaa">test</a>

#1


1  

A stronger solution:

更强的解决方案:

Set the data-productid to both the input and the test button:

将data-productid设置为输入和测试按钮:

var cart = { // JUST TO TEST
  add : function(productid, val){
    alert(productid +' '+ val);
  }
}

$(function () { // DOM ready

  $('.qtyplus, .qtyminus').on('click',function(){
    var $qty    = $('.featured-shopping-qty');
    var currVal = Math.abs( parseInt($qty.val(), 10) );
    var isPlus  = $(this).hasClass("qtyplus");
    var calc    = currVal + (isPlus? 1 : -1)
    $qty.val( (!isNaN(calc) && calc>=0) ? calc : 0);
  });
  
  $(document).on("click", ".throwToBasket", function(){
    var productid = $(this).attr("data-productid");
    var val  = parseInt( $("input[data-productid='"+ productid +"']").val() , 10);
    cart.add(productid, val);
  });
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="qtybox">
  <input type="text" name="quantity" value="0" class="qty featured-shopping-qty" data-productid="aaaaa">
</div>
<div class="plusminus">
  <div><input type="button" value="+" class="qtyplus"></div>
  <div><input type="button" value="-" class="qtyminus"></div>
</div>
<a href="javascript:void(0);" class="throwToBasket" data-productid="aaaaa">test</a>