[英]JavaScript does not detect clicks on td
JavaScript 沒有檢測到對表格單元格的點擊,代碼不起作用。 代碼:
document.querySelectorAll("td").forEach(e => e.addEventListener("click", function(){
console.log(this.cellIndex);
console.log(this.innerText);
console.log(document.querySelectorAll("th")[this.cellIndex].innerText);
}));
如果我將此代碼粘貼到控制台中,它可以工作,但作為單獨的 .js 文件或在 html 代碼中,它不起作用。 有什么問題嗎?
如果您將上述代碼鏈接為單獨的 JS 文件,並且您的導入腳本標簽位於 <head> 中,請確保所有與 DOM 相關的函數必須位於 DOMContentLoaded 或加載事件回調中。
對於這種情況,將外部 js 文件中的腳本更改為:
onload = () => {
document.querySelectorAll("td").forEach(e => e.addEventListener("click", function(){
console.log(this.cellIndex);
console.log(this.innerText);
console.log(document.querySelectorAll("th")[this.cellIndex].innerText);
}));
}
編輯 1:
知道是Ajax之后,
首先,querySelectorAll 返回一個NodeList,它沒有forEach 方法。
使用 Array.from(document.querySelectorAll()).forEach 代替。
其次,將代碼放在AJAX創建td回調的回調中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.