2012-06-03 47 views
0

我有一個有趣的問題。使用jquery和鼠標處理添加表格

我想使用jquery將行添加到表中,之後使添加的行響應mouseover事件,但代碼不起作用。

問題是該行按預期添加,但不響應mouseover事件。

任何建議,將不勝感激。

Urmas。

守則如下:

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

回答

1

您必須使用on功能給事件偵聽器添加到您動態地添加元素。例如:

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

描述:附加的事件處理函數的一個或多個事件的選擇的元素。

(每馬蒂亞斯Buelens,誰指出現場功能已被棄用。)

+0

太好了!非常感謝你!這是問題。 –

+2

由於jQuery 1.7,['live'](http://api.jquery.com/live/)不贊成使用['on'](http://api.jquery.com/on/),現在是您的所有功能於一身的綁定功能。 $(「#table」)。on(「mouseover」,「.elem」,function(){...});' –

+0

@MattiasBuelens但是任何一個都可以,不是嗎?它看起來像**上**是一個更通用的功能,可以處理更多的場景。 – McGarnagle