我在购物商店工作,在购物车页面上有一个'删除从购物车中删除',当他们单击它时,出现了一个弹出窗口,以确认他们是否要删除它从购物车。我遇到的问题是弹出窗口只能在第一个项目上使用,其他弹出窗口只会带您回到页面的顶部。
这是我正在使用的代码。
删除文本
<td style="text-align: center">
<a href="#" id="cart_popup">X</a>
</td>
弹出式
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<p class="modal-index-title">Hey!</p>
<p class="modal-title">Are you sure you want to remove this?</p>
<div class="modal-confirm">
<span class="close">No!</span>
<p><a href="#" onclick="remove_item({{ item.variant.id }}); return false;">Yes</a></p>
</div>
</div>
</div>
脚本
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("cart_popup");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
ids应该是DOM元素唯一的,因此您的JS代码只会抓住cart_popup
元素的第一个实例并在此处应用onclick。
如果要使它应用于所有删除卡车按钮,请在其上添加CSSClass,然后将btn.onclick
功能应用于具有该类的按钮。
编辑:
示例:
var classname = document.getElementsByClassName("classname");
var showModal = function() {
modal.style.display = "block";
};
for (var i = 0; i < classname.length; i++) {
classname[i].addEventListener('click', showModal, false);
}
您可能有几个具有相同id
属性的元素。只有第一个触发您的btn.onclick
功能。