提问者:小点点

jquery val()会自动从number更改为undefined


我有一个“输入”快把我逼疯了。输入从PHP函数“回显”到HTML页面中。

    '<td class="product-quantity" data-title="Quantity">
                            <div class="quantity">
                <label class="screen-reader-text" for="quantity_5ed41a96cc5c6">Casual shirt quantity</label>
        <input
            type="number"
            id="input'.$e.'"
            class="qtychg input-text qty text"
            step="0.5"
            value="'.$arr[$e]['quantity'].'"
            size="4"
            inputmode="numeric" />
                <span class="product-qty-arrows">
            <span id="'.$e.'" class="product-qty-increase lnr lnr-chevron-up"></span>
            <span id="'.$e.'" class="product-qty-decrease lnr lnr-chevron-down"></span>
        </span>
        </div>
                            </td>'

我可以使用span“class=”product-qty-recish“(调用以下javascript脚本)增加/减少输入值:

<script>
$('span').click(function (){

var Id=$(this).attr('id');
var val=$('#input'+Id).val();
var className= this.className;

if(className == "product-qty-increase lnr lnr-chevron-up"){

    val++;

}else if(className == "product-qty-decrease lnr lnr-chevron-down"){

    val--;
}

alert(val);

 $.ajax({
                        type: "POST",
                        url: "actions.php?action=chgQty",
                        data: "key=" + Id +"&val=" + val ,
                        success: function(result) { 
                          location.reload();
                        }
                     })


});
</script>

让我抓狂的问题有2个:

1)弹出“alert(val);”两次!!!!一次是正确的数字,第二次是“undefined”

2)显然,我不能发送$.ajax调用,因为该值变成了未定义值。

知道吗???


共1个答案

匿名用户

原因是您有嵌套的跨度,并且要将事件处理程序绑定到所有的跨度。当您单击向上或向下跨距时,事件会冒出到并在那里激发。

使用一个更具体的选择器,这样您只绑定到向上和向下按钮。

null

$('span.lnr').click(function() {

  var Id = $(this).attr('id');
  var val = $('#input' + Id).val();

  if ($(this).hasClass("product-qty-increase")) {
    val++;
  } else if ($(this).hasClass("product-qty-decrease")) {
    val--;
  }

  alert(val);

  $.ajax({
    type: "POST",
    url: "actions.php?action=chgQty",
    data: {key: Id, val: val},
    success: function(result) {
      location.reload();
    }
  })
});