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>
有人知道怎么做吗?
答案 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