<!DOCTYPE HTML>
<html>
        <head>
                <meta http-equiv="content-type" content="text/html; charset=UTF-8">
                <title>代码怎样写才能找到文档装载后新建的节点?</title> <script type="text/javascript" src="./jquery-1.4.2.js"></script>
                <script type="text/javascript">
                //文档装载完毕后新加一个A
$(document).ready ( function () {
$("div#nihao").append("<a id=\"hello\" href=\"http://www.g.cn\">Google2</a>");
});
</script>                <style type="text/css">
                </style>
        </head>        <body>
<div id="nihao">
<a id="first" href="http://www.g.cn">Google1</a>
</div>
                <script type="text/javascript">
                //阻止链接跳转(失败)
$("#hello").click (function (event) {
alert("nihao");
event.preventDefault();
});
                //阻止链接跳转(成功)
$("#first").click (function (event) {
alert("nihao");
event.preventDefault();
});
                </script>
        </body>
</html> $("#hello").click (function (event) {
alert("nihao");
event.preventDefault();
});
这段代码没起作用,显然对后加到文档中的节点无视了!
请问这是怎么回事?这个问题能解决吗?谢谢!!!

解决方案 »

  1.   

    这个是这样的,在你加载次函数并没有生成这个标签,所以你在生成标签的时候追加事件, $("div#nihao").append("<a id=\"hello\" href=\"http://www.g.cn\" click='test(event)'>Google2</a>");
     function test(){
    alert("nihao");
    event.preventDefault();
    }只能这样
      

  2.   

    $('div[id="lga"]').append("<a id=\"hello\" href=\"http://www.g.cn\">Google2</a>");
      

  3.   

    这个就不知道了,我用的 jquery-1.2.6.js、IE6
    也许是2、3楼说的那样吧,反正我这里是正常的
      

  4.   

     $(document).ready ( function () {
                $("div#nihao").append("<a id=\"hello\" href=\"http://www.g.cn\">Google2</a>");
    //对象添加后再绑定,setTimeout防止对象未创建完成
    setTimeout(function(){
           //阻止链接跳转(失败)
            $("#hello").click (function (event) {
                alert("nihao");
                event.preventDefault();
            });
    },0);//
            });
      

  5.   

    哦,我是在Ubuntu 10.04下面的chromium测试的
    您说的正常,是指event.preventDefault();起作用,成功阻止链接跳转吗?
      

  6.   


                    <script type="text/javascript">
                    //文档装载完毕后新加一个A
            $(document).ready ( function () {
                $("div#nihao").append("<a id=\"hello\" href=\"http://www.g.cn\">Google2</a>");
            $("#hello").click (function () {
                alert("nihao");
                return false;//阻止默认事件
            });
                    //阻止链接跳转(成功)
            $("#first").click (function () {
                alert("nihao");
                return false;//阻止默认事件
            });
            });
            </script>
    原来代码不能执行的原因在于,$("#hello").click (function (event) {
    alert("nihao");
    event.preventDefault();
    });执行的时候文档中还没有 #hello这个 元素,如果是要为未来要加进来的元素绑定事件的话,请用
    live
    $('.clickme').live('click', function() {
      alert("Live handler called."); 
    });
      

  7.   

    下面的js脚本先执行,而这时google2这个href还没产生,所以绑定的click事件不会执行
      

  8.   

    live方法在IE6下面好像还是不行!