<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
$("h2").html("<p class='test'>click me</p>")
});
$(".test").click(function(){
alert();
});
});
</script>
</head>
<body>
<h2></h2>
<button>generate new element</button>
</body>
</html>
我试图通过单击按钮在<h2>中生成一个类名为test的新标记。我还定义了一个与test关联的单击事件。但是这个事件不起作用。
有人能帮忙吗?
我不能让live或委托在一个灯箱(小盒子)中的div上工作。
我成功地使用了setTimeout,以以下简单的方式:
$('#displayContact').click(function() {
TINY.box.show({html:'<form><textarea id="contactText"></textarea><div id="contactSubmit">Submit</div></form>', close:true});
setTimeout(setContactClick, 1000);
})
function setContactClick() {
$('#contactSubmit').click(function() {
alert($('#contactText').val());
})
}
另一种更简洁的方法(IMHO)是使用一个原始的javascript函数来响应一个on click事件,然后将目标元素传递回jQuery。这种方法的优点是你可以在任何地方动态地添加你的元素,点击处理程序将“正常工作”,你不需要担心把控制委托给父元素,等等。
步骤1:更新动态html以触发onclick事件。确保将'event'对象作为参数传递
$("button").click(function() {
$("h2").html("<p class='test' onclick='test(event)'> click me </p>")
});
步骤2:创建测试函数以响应单击事件
function test(e){
alert();
});
可选步骤3:鉴于您正在使用jQuery,我假设它将有用的引用返回到源按钮
function test(e){
alert();
// Get a reference to the button
// An explanation of this line is available here
var target = (e.target)? e.target : e.srcElement;
// Pass the button reference to jQuery to do jQuery magic
var $btn = $(target);
});