首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >JavaScript -如何使用事件侦听器从HTML中获取值

JavaScript -如何使用事件侦听器从HTML中获取值
EN

Stack Overflow用户
提问于 2018-06-26 03:58:13
回答 1查看 46关注 0票数 0

我一直在为我的商店做一个编码项目,并且遇到了一个问题--“从购物车中移除商品”。

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

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

我正在尝试获取点击的每个按钮的值。查看函数removeItem

代码语言:javascript
复制
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);
}

EN

回答 1

Stack Overflow用户

发布于 2018-06-26 04:16:52

你的问题是你正在使用

代码语言:javascript
复制
document.querySelector('.remove-btn')

以获取对该元素的引用。这将只获得它看到的第一个.remove-btn,而不是每次调用后队列中的下一个。

将你的元素传递给你的函数,这样你就可以获得对它的正确引用。

代码语言:javascript
复制
<div class = "remove-btn" value = "${j}"><button onclick="removeItem(this.parentElement)">Remove Item</button></div>

this将引用<button>。顾名思义,parentElement将是父元素,在本例中是.remove-btn元素。

并将removeItem函数更改为

代码语言:javascript
复制
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);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51031007

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档