为了账号安全,请及时绑定邮箱和手机立即绑定

jquery val() 自动从数字变为未定义的时间

jquery val() 自动从数字变为未定义的时间

慕慕森 2022-10-08 17:15:51
我有一个让我发疯的“输入”。输入从 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>'我可以使用调用以下 javascript 脚本的 span "class="product-qty-increase" 来增加/减少输入值:<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)“警报(val);” 弹出两次!!!!一个带有正确的数字,第二个带有“未定义”2) 显然我不能发送 $.ajax 调用,因为值变成了未定义的。任何想法???
查看完整描述

1 回答

?
慕雪6442864

TA贡献1812条经验 获得超5个赞

原因是您有嵌套的跨度,并且您将事件处理程序绑定到所有这些跨度。当您单击向上或向下跨度时,事件也会冒泡<span class="product-qty-arrows">并在那里触发。


使用更具体的选择器,因此您只绑定到向上和向下按钮。


$('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();

    }

  })

});


查看完整回答
反对 回复 2022-10-08
  • 1 回答
  • 0 关注
  • 121 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号