2011-10-05 122 views
0

这是我下的test.html文件追加jQuery代码和点击功能?

<!DOCTYPE html> 
    <html> 
     <head> 
      <style> 
       p { 
        background:yellow; 
       } 
       .content{ 
        width:40px; 
        margin:0px 30px; 
       } 
      </style> 
      <script src="http://code.jquery.com/jquery-latest.js"></script> 
      <script> 
       $(document).ready(function(){ 
        $('#test').click(function(){ 
        // alert("test"); 
        var htmlData='<div class="resizable" ><div class="content">test</div></div>'; 
        $('.container').append(htmlData); 
        }); 
        $('.content').click(function(){ 
        alert("test"); 
        }); 
       }); 
      </script> 
    </head> 
    <body> 
     <div class="container"> 
      <div class="resizable" > 
       <div class="selected content">Time</div> 
       <button type="button" id="test">Click Me!</button> 
      </div> 
     </div> 
    </body> 
</html> 

当我点击一个div追加我有上点击功能写入也类内容的内容类确实呼吁alert.The jQuery的点击功能按钮调用硬编码的内容类,但不调用由buttton的点击函数附加的内容类。

回答

0

您需要使用直播功能,用于动态创建的DOM元素 - http://api.jquery.com/live/

$('.content').live('click', function(){ 
    alert("test"); 
}); 
+1

或者委托()http://api.jquery.com/delegate/ – Arda

+0

@matino感谢您的帮助。 –

0
$("body").delegate("#test", "click", function(){ 
     //write your code here 
});