2017-06-29 70 views
0

我正在shopify商店工作,購物車頁面上有一個'刪除購物車'選項,當他們點擊它時彈出窗口顯示確認是否要刪除它從購物車。 我遇到的問題是彈出窗口只能在第一個項目上工作,其他人只會將您帶回頁面的頂部。Pop up modal只適用於第一項

這是我使用的代碼。

刪除文本

<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"; 
     } 
    } 

回答

1

的ID應該是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); 
} 
+0

感謝Erick的回覆,這很有道理! 你能給我一個例子,我只是嘗試應用一個CSSclass,但那導致它不加載。 – tbar

+0

那麼你必須從根本上改變你的代碼,使它與一個類一起工作,就像你使用一個類選擇器代替一樣,Javascript代碼將返回一個元素數組(因爲有多個使用類) 我編輯了我的答案以添加示例代碼。 –

+0

非常感謝,編輯幫了我很大的忙! – tbar

0

你可能有相同的id屬性的幾個要素。只有第一個觸發你的btn.onclick功能。