【问题标题】:JavaScript - How to Obtain Value from HTML with Event ListenerJavaScript - 如何使用事件监听器从 HTML 中获取值
【发布时间】:2018-12-04 11:22:24
【问题描述】:

我一直在为我的商店做一个编码项目,但遇到了一个功能——“从购物车中删除商品”

我发布的代码执行以下操作:从“购物车”数组中获取数据,并使用 for 循环将每个产品项推送到 DOM。例如,如果购物车中有三件商品,则将显示 3 行。

我的问题是尝试删除单个订单项。我的“删除”按钮仅适用于添加的最后一个产品(在 3 个订单项的情况下 - “索引 #2)。它不会识别索引 0 和索引 1 处的 j 值。

我试图获取每个单击按钮的值。 查看函数 removeItem

function displayCart() {
	var cartItem = JSON.parse(sessionStorage.getItem("cartSS"));
	if (cartItem != null) {
		var cart = cartItem;
	}else {
		var cart = [];
	}
	if (cart.length == 0) {
		var emptyCartMessage = document.getElementById('product-container');
		emptyCartMessage.insertAdjacentHTML('afterend', '<div id ="emptyCart">Your Cart is Empty</div>');
		document.getElementById('subtotal').style.display = "none";
	} else {
		var productLine = document.getElementById('product-container');
		var subTotal = 0;
		for (var j in cart) {
			var productName = productNameObj[cart[j].productID];
			var lineTotal = parseInt(cart[j].quantity) * (cart[j].price);
			
			subTotal+= lineTotal;
			
			productLine.insertAdjacentHTML('afterend', `<div class="product-line"><img id = "cart-img" src="img/${cart[j].productID}.jpg" alt="cart"><div id = "cart-product"><h3 id = "product-name">${productName}</h3><p id = "product-size">Size: ${cart[j].size}</p></div><div id = "cart-price"><h3 id = "heading-price">Item Price</h3><p id = "product-price">(${cart[j].quantity}) x $${cart[j].price} = $${lineTotal.toFixed(2)}</p></div><div class = "remove-btn" value = "${j}"><button onclick="removeItem()">Remove Item</button></div></div>`);
		}
		document.getElementById('subtotal').textContent = "Subtotal: $" + subTotal;
	}
}

function removeItem (){
	var cart = JSON.parse(sessionStorage.getItem("cartSS"));
	
	var btnIndex = document.querySelector('.remove-btn').getAttribute("value");
	console.log(cart[btnIndex]);
	console.log(btnIndex);
}

【问题讨论】:

  • 不要将for .. in 用于数组,因为您可能会意外地迭代数组的其他属性(如方法),而不仅仅是索引属性(即1、2、3 等)。请改用for ... of

标签: javascript html arrays dom


【解决方案1】:

你的问题是你正在使用

document.querySelector('.remove-btn')

获取对元素的引用。这只会得到第一个.remove-btn,它不会在每次调用后看到下一个。

将您的元素传递给您的函数,以便您可以正确引用它。

<div class = "remove-btn" value = "${j}"><button onclick="removeItem(this.parentElement)">Remove Item</button></div>

this 将引用&lt;button&gt;。而parentElement,顾名思义,在这种情况下将是您的.remove-btn 元素的父元素。

并将removeItem 函数更改为

function removeItem (removeBtn){
    var cart = JSON.parse(sessionStorage.getItem("cartSS"));

    //var btnIndex = document.querySelector('.remove-btn').getAttribute("value");
    var btnIndex = removeBtn.getAttribute('value');
    console.log(cart[btnIndex]);
    console.log(btnIndex);
}

【讨论】:

  • 谢谢帕特里克,我已经想了好几个小时。对此,我真的非常感激。我正在自学入门 Web 开发,希望能转行。这意味着很多。再次感谢您。
猜你喜欢
  • 2020-06-21
  • 1970-01-01
  • 2014-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-06
  • 1970-01-01
相关资源
最近更新 更多