+ -
当前位置:首页 → 问答吧 → jQuery使用html方法动态生成的元素为什么无法使用?

jQuery使用html方法动态生成的元素为什么无法使用?

时间:2010-01-13

来源:互联网

复制代码
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3.     <head>
  4.         <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  5.         <title>Insert title here</title>
  6.         <script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js">
  7.         </script>
  8.         <script type="text/javascript">
  9.             $(document).ready(function(){
  10.                 $("#btn1").click(function(){
  11.                     $("#div1").html("<a href=\"#\" id=\"demo\">动态元素</a>");
  12.                 });
  13.                 $("#demo").click(function(){
  14.                     alert("动态HTML元素");
  15.                 });
  16.             })
  17.         </script>
  18.     </head>
  19.     <body>
  20.         <input type="button" id="btn1" value="动态元素" />
  21.         <div id="div1">
  22.         </div>
  23.     </body>
  24. </html>


将上面的代码另存为htm文件,打开点击按钮《动态元素》 ,在div1里面出现的a标签元素的事件为什么无效呢?

作者: x900   发布时间: 2010-01-13

顺序的问题

一开始,就没有<a  id = "dome"></a>这个元素,是点了按钮之后才创建的,所以一开始的绑定就失败了。

试着这样就可以了,当然也有其它的解决方法:
$(document).ready(function(){
                $("#btn1").click(function(){
                    $("#div1").html("<a href=\"#\" id=\"demo\">动态元素</a>");
                     $("#demo").click(function(){
                        alert("动态HTML元素");
                       });
                });
              
            })


初来乍到,相互学习。

作者: position   发布时间: 2010-01-13

$("#btn1").click(function(){
                    $("#div1").html("<a href=\"#\" id=\"demo\">动态元素</a>");
                });
                $("#demo").click(function(){
                    alert("动态HTML元素");
                });

因为demo是动态生成所,如果你想给他绑定事件需要用live或bind
$("#demo").live("click",function(){
                    alert("动态HTML元素");
                });

这样就没问题了

作者: ssvfdn   发布时间: 2010-01-14

相关阅读 更多