[英]Unable to click button in dynamically created table cell
我正在動態創建一個表,其中每行末尾都有按鈕。
問題是,我無法使懸停效果起作用。 如果我也將按鈕設置為eventlistener,則只有div上設置的eventlistener才會拍攝。 當然,如果僅在按鈕上設置事件監聽器,則什么也不會發生。
else if (j == 5) {
//if it's the 5th column in the table, create a button in each row.
td.className = 'editrow';
var edit_btn = document.createElement('button');
edit_btn.innerText = "Edit";
edit_btn.className = 'edit_word';
td.appendChild(edit_btn);
td.addEventListener("click", function() {
//This shoots: when I click on the table cell (so on the button or outside it)
//I cannot set edit_btn.addEventListener, it doesn't do anything
console.log("clicked");
});
}
我相信按鈕蓋在td上(或后面),這就是懸停不起作用的原因。
此圖像可以幫助您進行想象。 黃色背景顏色是將鼠標懸停在td上方(使其成為td或其中的按鈕)時拍攝的懸停效果。 按鈕的設計從未改變,我再次檢查了它應該是的,是的,css是正確的。
您可以在頁面的開頭部分嘗試以下腳本:
<script>
document.addEventListener('click',function(e){
if(e.target && e.target.className== 'edit_word'){
console.log("clicked")
}
});
</script>
並從代碼中刪除td.addEventListener方法
或使用jQuery
<script>
$(function(){
$(document).on('click','.edit_word',function(){
console.log("clicked");
});
});
</script>```
您發布的代碼可以正常工作。 也許還有其他問題,例如CSS指針事件覆蓋或HTML結構問題。 如果右鍵單擊按鈕並選擇“檢查元素”,會突出顯示哪個元素會發生什么?
https://jsfiddle.net/amsv/tk3jbcms/
<table>
<tbody>
<tr>
<td id="td"></td>
<td id="result"></td>
</tr>
</tbody>
</table>
var td = document.getElementById("td");
var clicked = 0;
td.className = 'editrow';
var edit_btn = document.createElement('button');
edit_btn.innerText = "Edit";
edit_btn.className = 'edit_word';
td.appendChild(edit_btn);
edit_btn.addEventListener("click", function() {
// Logging number of times clicked..
var result = document.getElementById("result");
result.innerHTML = "Clicked: " + clicked++ + " times."
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.