它使用div在身体上工作。它不使用get

时间:2012-12-28 08:07:51

标签: javascript jquery html get click

状态:工作

顺利运行 - 点击工作

Jquery的

 $("document").ready(function(){

    $("#test").click(function(){
        alert("abc");
    });     
 });

CSS

.blue {
background-color:blue;
}

标记正文

<body>
<div class="blue" id="test">Testing code</div>
</body>

状态:不工作

成功添加文件并在其中添加test,但点击不起作用

Jquery的

 $("document").ready(function(){

    $.get("new.php", {
         // this math avoids IE from crashing
         nbRandom: Math.random() 
         },
         function(data){
         $("body").html(data);
         });

    $("#test").click(function(){
        alert("abc");
    });   
 });

CSS

.blue {
background-color:blue;
}

标记正文

<body>
</body>

有人知道怎么做吗?

4 个答案:

答案 0 :(得分:5)

方法get是异步的,这意味着当ajax请求仍在运行时,流将继续,最佳解决方案是将点击处理程序放入get回调。

$("document").ready(function(){

$.get("new.php", {
     // this math avoids IE from crashing
     nbRandom: Math.random() 
     },
     function(data){
       $("body").html(data);
       $("#test").click(function(){
         alert("abc");
       });   
     });


});

答案 1 :(得分:4)

您应该从元素或文档对象的静态父级之一委派事件。

$(document).on("click", "#test", function(){
    alert("abc");
})

答案 2 :(得分:1)

使用委托 (推荐)

$(function() {
  $('body').on('click', '#test', function() { alert('abc'); });
  // or
  // $('body').delegate('#test', function() { alert('abc'); });
});

答案 3 :(得分:0)

问题是click函数在附加div的{​​{1}}之前被调用...

在附加div之后调用click函数..以便它获取id ...和事件

试试这个

#test

$.get("new.php", { // this math avoids IE from crashing nbRandom: Math.random() }, function(data){ $("body").html(data); $("#test").click(function(){ alert("abc"); }); }); 函数,选择器为on ..(我总是喜欢这样做)

document