鼠标不适用于动态内容

Mouseenter not working for dynamic content

本文关键字:动态 适用于 不适用 鼠标      更新时间:2023-09-26

我写了一段代码,当鼠标移到特定元素时,我需要在其中触发一个功能。

以下代码适用于所有静态

$("table td").on("mouseenter",function(){
    console.log("mouse entered")
});

但对于所有动态CCD_ 1事件,即使我使用以下代码,也不会触发

$("table td").on("mouseenter",".editcolumn",function(){
    console.log("mouse entered")
});

知道如何让它发挥作用吗。我使用的是jQuery 1.11

我知道我刚刚发表了评论,但我想我会给你看一个例子:

HTML:

<table id="tablee" cellspacing="0">
    <thead>
        <tr class="tablehead">
            <th>This</th>
            <th>is</th>
            <th>a</th>
            <th>table</th>
            <th>header</th>
            <th>and</th>
            <th>stuff</th>
            <th>though</th>
        </tr>
    </thead>
    <tr class="append">
        <td class="edit-column">asdf</td>
        <td class="edit-column">qwer</td>
        <td class="edit-column">zxcv</td>
        <td class="edit-column">rtyu</td>
        <td class="edit-column">tyui</td>
        <td class="edit-column">dfgh</td>
        <td class="edit-column">dfgh</td>
        <td class="edit-column">wert</td>
    </tr>
    <!-- ... -->
</table>
<br/>
<br/>
<input type="button" class="add-column" value="Add Column" />


Javascript:

$(function() {
    $('.add-column').click(function() {
        $('.append').append("<td class='edit-column'>iueo</td>");
        $('.tablehead').append("<th>Mo columns</th>");
    });
                                  /*  vvv - this   */
    $("#tablee").on('mouseenter', '.edit-column', function() {
    /* ^^^ should be children or a child of this */
        $(this).css('background-color', 'yellow');
    });
});



这是一把小提琴

这个问题的答案可以更好地解释委托事件。

对于添加或删除的动态元素,我也面临着类似的问题。在这种情况下,您可以创建动态元素,并将事件处理程序附加到它们的属性上,即在您的情况下,可以将所需的操作放入由属性事件处理程序调用的函数中:

应该是这样的:

Javascript:

 function whenMouseEnters() {
    // perform some operations
 }

Html:

<td onmouseenter="whenMouseEnters()">

如果表在DOM加载时可用,您可以使用类editColumntd编写delgated事件,如下所示:

$("table").on("mouseenter",".editcolumn",function(){
   console.log("mouse entered")
 });
相关文章: