【问题标题】:jquery val() change automatically from number to undefined in the timejquery val() 自动从数字变为未定义的时间
【发布时间】:2020-06-17 19:28:39
【问题描述】:

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

有什么想法???

【问题讨论】:

  • 您不应该为多个元素使用相同的 ID。
  • 不要检查整个className变量,而是使用if ($(this).hasClass("product-qty-increase")
  • 选择类$('.lnr ')而不是span

标签: javascript jquery ajax


【解决方案1】:

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

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

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

【讨论】:

  • 谢谢!!!!!!有效 !!!!我快疯了....
  • 在调用$.ajax之前添加if( val !== undefined)
  • @EhsanNazeri 输入的值永远不能不确定,它总是一个字符串。只有当输入不存在时才会发生这种情况。
  • 嗨 EhsanNazeri,正如 Barmar 所说,我正在“将事件处理程序绑定到所有事件处理程序”,所以我从我单击的跨度中获得了第一个值,第二个(未定义)来自我点击的跨度没有点击
猜你喜欢
  • 2011-03-03
  • 2021-09-06
  • 2016-12-01
  • 1970-01-01
  • 2021-05-16
  • 2017-10-27
  • 1970-01-01
  • 1970-01-01
  • 2012-06-22
相关资源
最近更新 更多