猿问

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

我有一个让我发疯的“输入”。输入从 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 调用,因为值变成了未定义的。

任何想法???


慕慕森
浏览 122回答 1
1回答

慕雪6442864

原因是您有嵌套的跨度,并且您将事件处理程序绑定到所有这些跨度。当您单击向上或向下跨度时,事件也会冒泡<span class="product-qty-arrows">并在那里触发。使用更具体的选择器,因此您只绑定到向上和向下按钮。$('span.lnr').click(function() {&nbsp; var Id = $(this).attr('id');&nbsp; var val = $('#input' + Id).val();&nbsp; if ($(this).hasClass("product-qty-increase")) {&nbsp; &nbsp; val++;&nbsp; } else if ($(this).hasClass("product-qty-decrease")) {&nbsp; &nbsp; val--;&nbsp; }&nbsp; alert(val);&nbsp; $.ajax({&nbsp; &nbsp; type: "POST",&nbsp; &nbsp; url: "actions.php?action=chgQty",&nbsp; &nbsp; data: {key: Id, val: val},&nbsp; &nbsp; success: function(result) {&nbsp; &nbsp; &nbsp; location.reload();&nbsp; &nbsp; }&nbsp; })});
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答