-1
我剛開始使用JQuery,我有一個問題,關於爲dinamically創建的按鈕添加一個單擊事件偵聽器。事件監聽器(單擊)爲新的元素。jQuery
所以當用戶點擊第一個按鈕時,我的第一個功能只需將第二個按鈕添加到div中。 問題是,使用相同的方法,我的第二個按鈕的偵聽器不工作。 這裏是我試圖做的一個簡單的例子。
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//listener for first button
$("#button1").click(function(event){
event.preventDefault();
$("#newElement").append("<input type='button' id='button2' value='Need listener for this new button'>");
});
//listener for the seccond button (problematic one)
$("#button2").click(function(event){
event.preventDefault();
alert("Second button clicked!");
});
});
</script>
<title>Exemple JQuery</title>
</head>
<body>
<input type="button" id="button1" value="Add a new button dynamically">
<div id="newElement">
</div>
</body>
</html>
任何想法都非常受歡迎。謝謝