2012-03-19 25 views
1

我只是新的jquery,而在jQuery上做实验时我遇到了这个问题 - >它可以将html插入到div中,但点击函数不能处理插入的html。有人知道为什么在此先感谢Onclick函数不能在插入的HTML上工作

$(document).ready(function(){ 
$("#insertTest").click(function(){ 
$("#testDiv").html($("#testDiv").html() + '<p><a href="#" class="testClick">Click Me</a></p>'); 
}); 

$(".testClick").click(function(){ 
alert('Ahoy'); 
}); 

}); 

<a href="#" id="insertTest">Click to Insert</a> 
<div id="testDiv"> 
</div> 

回答

1

使用方法live()

$('.testClick').live('click', function(){ 
    alert('Ahoy'); 
}); 

编辑:支持jQuery的1.7+标准,使用的.on()代替.live()

+1

由于jQuery 1.7中.live()已被弃用在fav或.on()。 – j08691 2012-03-19 02:58:07

+0

谢谢,更新OP – 2012-03-19 03:00:06

+0

我已经发现了**。live **,它的工作原理,感谢所有的反馈人员,我真的很喜欢它,再次感谢 – 2012-03-19 03:39:15

2

使用.on()方法http://api.jquery.com/on/.live()被弃用为了确保未来的兼容性,请使用on()live()

http://api.jquery.com/live/

在jQuery 1.7的,所述.live()方法被弃用。使用.on()连接到事件处理程序 。老版本jQuery的用户应该优先使用 .delegate(),而不是.live()。

$('.testClick').on('click', function(){ 
    alert('Ahoy'); 
}); 
0

你可以使用.live,但它已被弃用,使用.on代替。你可以用.append来插入html。

$("#insertTest").click(function() { 
    $("#testDiv").append('<p><a href="#" class="testClick">Click Me</a></p>'); 
}); 

$("#testDiv").on('click', '.testClick', function() { 
    alert('Ahoy'); 
});