[英]JavaScript For Loop not returning anything (not running)?
好的,我在我的 EJS 頁面上的腳本標簽中有這個 for 循環。 當前代碼如下所示:
<script async>
var removeCartItemButtons = document.getElementsByClassName('btn-danger')
console.log(removeCartItemButtons)
var i;
for (i = 0; i < removeCartItemButtons.length; i++){
console.log('elem')
var button = removeCartItemButtons[i]
button.addEventListener('click', function() {
console.log('clicked')
})
}
</script>
removeCartItemButtons 的 console.log 工作,但 console.log('elem') 不運行。 我的 cmd 和開發人員工具中都沒有錯誤。 我在不同的論壇上在線查看,發現人們對我做類似的事情並且他們的工作很好。
我已經嘗試了多種方法,另外需要注意的是,這是在 html 文件中而不是外部文件。
這個 for 循環的最終目標是遍歷每個類為 'btn-danger' 的元素,並在它們被點擊時記錄。 任何幫助都會很棒!
嘗試在控制台中運行 document.getElementsByClassName('btn-danger') 。
附加提示:js 中有一個 for of 循環
檢查這個: https : //developer.mozilla.org/de/docs/Web/JavaScript/Reference/Statements/for...of基本上:
for(let button of removeCartItemButtons) {
button.addListener
}
我在 Codepen 中嘗試了這段代碼,它奏效了。 我重寫了您的代碼,但從技術上講,只是使用了不同的語法。 腳本標簽中的“異步”可能會導致問題,我不確定。
var buttons = document.querySelectorAll('.btn-danger');
[...buttons].forEach(button => {
console.log('elem')
button.addEventListener('click', function() {
console.log('clicked')
})
})
您的 HTML 代碼肯定有問題。 運行下面的代碼片段,它工作正常
var removeCartItemButtons = document.getElementsByClassName('btn-danger') console.log(removeCartItemButtons) var i; for (i = 0; i < removeCartItemButtons.length; i++) { console.log('elem') var button = removeCartItemButtons[i] button.addEventListener('click', function() { console.log('clicked'); alert('clicked'); }) }
<button class='btn-danger'>Button</button> <br/> <button class='btn-danger'>Button</button> <br/> <button class='btn-danger'>Button</button> <br/> <button class='btn-danger'>Button</button>
removeCartItemButtons.length
為 0,因為當代碼片段運行時,DOM 未完全加載。
刪除async
並將您的腳本放在 html 的末尾。
另一種選擇是使用像onload
這樣的 EventListener 來確保您的按鈕在更改之前存在。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.