我得到了一个让我发疯的“输入”。输入从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>
让我抓狂的问题有两个:
1)弹出两次"alert(val);“!一次使用正确的数字,第二次使用"undefined“
2)很明显,我不能发送$.ajax调用,因为值正在变为未定义。
有什么想法吗?
发布于 2020-06-17 19:38:11
原因是您有嵌套的跨度,并且您将事件处理程序绑定到所有跨度。当您单击向上或向下跨度时,事件会向外冒泡到<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();
}
})
});
https://stackoverflow.com/questions/62436938
复制