2014-01-19 51 views
-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> 

任何想法都非常受欢迎。谢谢

回答

2

委托的事件处理程序动态插入的元素

$("#newElement").on('click', "#button2", function(event){ 
    event.preventDefault(); 
    alert("Second button clicked!"); 
});