【问题标题】:Undefine Input Value on function取消定义函数的输入值
【发布时间】:2019-12-05 19:14:16
【问题描述】:

我对此完全陌生,但我正在尝试使用 javaScript 制作购物车。 一切都很好,直到我尝试向添加到购物车的商品添加输入值。 我有一张图片、一个价​​格和一个名称,但我需要添加一个“数量”字段。

这是该字段的输入:

            
<input type="number" id="store-item-qty" type="qty" placeholder="QTY" name="text_name" class="store-item-qty">

这是我的脚本

//value of qty---->
let qty =
       event.target.parentElement.parentElement.nextElementSibling.children[0].children[2].value;
   //add items to cart--->    
 cartItem.innerHTML = ` 
            <img src="${item.img}" class="img-fluid" id="item-img" alt="">
            <div class="item-text">

              <p id="cart-item-title" class="font-weight-bold mb-0">${item.name}</p>
              <p>    </p>
              <span id="cart-item-girth" class="cart-item-girth" class="mb-0">${item.girth}</span>
            </div>
            <p class="store-item-qty" type="qty" id="store-item-qty">${item.qty}</p>
            <a href="#" id='cart-item-remove' class="cart-item-remove">
              <i class="fas fa-trash"></i>
            </a>
          </div>
          `;
          
//var qty--->
var qty = "qty";
document.getElementById("store-item-qty").value;

但是当我点击“添加到购物车”时,它会导入除 QTY 字段之外的所有信息并显示“取消定义”

【问题讨论】:

  • 请创建一个合适的minimal reproducible example
  • 您正在使用具有相同变量名的 letvar,这可能会导致您遇到一些问题。我建议检查一下
  • 好的,让我上传最小的可重现示例。

标签: javascript jquery html function input


【解决方案1】:

首先,您获取元素quantitiy 的值并将其定义为let qty = ...。 在您的模板中,您尝试从${item.qty} 读取qty

应该阅读${qty}AFAIK。

【讨论】:

  • 现在它显示为“[Object HTMLInputElement]”而不是“未定义”,我想几乎就在那里,但我错过了一些东西(抱歉对我来说是一种超级新语言哈哈)
  • 获取值后添加console.log(qty)。结果如何?
  • 它显示: ... .我猜是正确的,但我需要定义值??
  • 所以你得到了输入元素。你只需要读出元素的值。将${qty} 更改为${qty.value}
  • 成功了!!! OMG 我很高兴,谢谢!我只是在 let qty=..... 之后添加 .value 就可以了!!
猜你喜欢
  • 2022-01-23
  • 2019-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-24
  • 2015-01-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多