简体   繁体   中英

Unable to click button in dynamically created table cell

I am creating a table dynamically in which there are buttons at the end of each row.

The problem is, I can't make the hover effect work. If I set the eventlistener on the button as well, only the eventlistener set on the div shoots. Of course, if I set the eventlistener only on the button, nothing happens.

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

}

I believe the button is covered (or behind) the td and that is why the hover doesn't work.

This image may help it imagine. The yellow background color is a hover effect shot on hovering above the td (let it be the td or the button inside it). The design of the button never changes and I double checked it should be and yes, css is correct. 在此处输入图片说明

you may try the following script in head section of page :

<script>
document.addEventListener('click',function(e){
    if(e.target && e.target.className== 'edit_word'){
        console.log("clicked")
     }
 });
</script>

and remove the td.addEventListener method from your code

or using jQuery

<script>
$(function(){ 

   $(document).on('click','.edit_word',function(){ 

       console.log("clicked"); 

    });

 });
</script>```

The code you posted works fine. Perhaps there's something else amiss, like CSS pointer-event overrides or HTML structure problems. What happens if you right-click the button and choose "Inspect Element", which element does it highlight?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM