【问题标题】:Unable to click button in dynamically created table cell无法单击动态创建的表格单元格中的按钮
【发布时间】:2019-08-30 06:33:56
【问题描述】:

我正在动态创建一个表格,其中每行末尾都有按钮。

问题是,我无法使悬停效果起作用。如果我在按钮上也设置了事件监听器,那么只有在 div 上设置的事件监听器才会触发。当然,如果我只在按钮上设置事件监听器,什么都不会发生。

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 是正确的。

【问题讨论】:

    标签: javascript button hover


    【解决方案1】:

    您发布的代码运行良好。也许还有其他问题,例如 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."
    });
    

    【讨论】:

    • 您是否已经在 TD 上安装了一个可能使用 preventDefault 和/或 stopPropagation 方法的侦听器?或阻止指针事件的按钮 CSS。
    • 可能还想比较 z-indexes,如果你已经修改了这些。在浏览器开发者控制台的按钮上添加“z-index:9999”,看看有没有效果。
    • 终于!是你的 css 创意帮助我找到了这个小怪物:pointer-events: none; 我不知道它是如何到达那里的。
    【解决方案2】:

    您可以在页面的 head 部分尝试以下脚本:

    <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>```
    

    【讨论】:

    • 控制台中没有显示任何内容。这一定是代码块之外的其他内容
    • 这行不通,因为点击事件被 TD 捕获:)
    • 好的,你有 jQuery,如果你使用 jquery,那么你可以这样写: $(function(){ $(document).on('click','.edit_word',function() { console.log("clicked"); }); });
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-03
    • 1970-01-01
    • 2019-03-16
    • 2013-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多