使用 jquery 和鼠标处理添加表



我有一个有趣的问题。

我想使用 jquery 将行添加到表中,然后添加行以响应鼠标悬停事件,但代码不起作用。

问题是行按预期添加,但不响应鼠标悬停事件。

任何建议将不胜感激。

乌尔马斯。

代码如下:

<head>
  <style type="text/css">
  .elem {
    color: purple;
    background-color: #d8da3d 
    }
  </style>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js">
</script>   

</head>
<body>
<table id="table">
   <thead>  
    <tr>
        <th>Numbers</th>
        <th>Letters</th>
        <th>Symbols</th>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td class='elem'>111</td>
        <td class='elem'>aaa</td>
        <td class='elem'>@@@</td>
    </tr>
    <tr>
        <td class='elem'>222</td>
        <td class='elem'>bbb</td>
        <td class='elem'>###</td>
    </tr>
    <tr>
        <td class='elem'>888</td>
        <td class='elem'>iii</td>
        <td class='elem'>???</td>
    </tr>
    </tbody>        
</table>
<input type = "button" id = "add" value = "add row" />

<script type="text/javascript">
$(".elem").mouseover(function() {
alert("over");
});
$("#add").click(function() {
$row_to_add="";
$row_to_add+="<tr>";
    $row_to_add+="<td class='elem'>999</td>";
    $row_to_add+="<td class='elem'>qqq</td>";
    $row_to_add+="<td class='elem'>&&&</td>";
$row_to_add+="</tr>";
 $("#table tr:last").after($row_to_add);
});

</script>
</body>

您必须使用 on 函数将事件侦听器添加到动态添加的元素中。 例如:

$(document).on(".elem", "mouseover", function() {
    //...
}

说明:将一个或多个事件的事件处理程序函数附加到所选元素。

(根据Mattias Buelens,他指出实时函数已被弃用。

最新更新