2017-02-22 39 views
0

這些我編寫的代碼當用戶點擊模式外的任何地方時,關閉它,但它不工作,我的代碼有什麼錯誤。 「盒子搜索」,「登錄」,「註冊」元素ID名稱。這些我編寫的代碼當用戶點擊模式外的任何地方時,關閉它但它不工作。我的代碼中有什麼錯誤

​​
+2

的可能的複製[JavaScript的閉包內環路 - 簡單實用的例子(http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Xufox

+0

每次迭代循環時,都會抹掉window.onclick的最後一個值並將新函數設置爲其值。使用'.addEventListener()'註冊事件處理程序。 –

回答

1

每次你通過你的循環迭代時間,您是window.onclick消滅了最後一個值,並創下新的功能作爲其值。使用.addEventListener()來註冊事件處理程序。

現在,說了這樣的話,在回調函數中使用i時會出現問題,因爲i被聲明爲更高級別,所以會在其周圍創建閉包。你可以閱讀更多關於關閉here。關閉導致事件處理函數都在尋找modal[3],因爲這是循環退出時最後一個值i被設置爲。

爲了避免關閉和糾正window.onclick重寫,腳本應該是:

<script> 
    // Use modern standards to set up event handlers: 
    window.addEventListener("click", testModal) 

    function testModal(event){ 
    var modal = ["box-search","login","register"]; 

    // Use the built-in Array.prototype.forEach method to loop 
    // through the array elements, thus avoiding a numeric counter 
    modal.forEach(function(element){ 
     // Search the DOM for elements that have id'sthat 
     // match the modal array's id's 
     var el = document.getElementById(element); 

     // Check the found element 
     if (event.target == el) { 
      el.style.display = "none"; 
     } 
    }); 

    }  
</script> 
+0

其工作。非常感謝你 – Baswaraj

+0

@Baswaraj不客氣。不要忘記投票答案,幫助你。 –

0

你window.onClick是錯誤的:

1 - 你在函數外的模態循環,你應該做的裏面讓它正常工作

2 - 你event.target比較模態數組元素,而不是它的id

3-嘗試一種風格分配給一個字符串(模式[1]),而不是你的event.target對象

這是重編寫的函數(它應該工作)

window.onclick = function(event) { 

for(var i=0;i<3;i++) { 
    if (event.target.id == modal[i]) { 
    event.target.style.display="none"; 
    } 
} 
} 
相關問題