在由jQuery .html()函数插入的元素上绑定事件处理程序

时间:2011-02-15 12:39:25

标签: javascript jquery html javascript-events html-rendering

在ajax调用我的网站后,我用.html()渲染一些新内容。

$.getJSON(scriptURL, $("#domainForm").serialize(), function(data) {
  $("#checkedDomain").html(data['html']) 
});

现在。如何在不替换脚本的情况下将事件处理程序绑定到替换的html中的div标签? 现在我渲染到我的网站的html看起来像这样:

<script type="text/javascript" src="myScript.js"/>
<div id="tagWithHandlerOn"/>someButton</div>

我想摆脱&lt; script&gt;标记,因为它是重新声明,如果我再次将相同的内容加载到该标记中,则将加载2个脚本。任何提示?

2 个答案:

答案 0 :(得分:2)

尝试使用jQuery.live()


  

从jQuery 1.7开始,不推荐使用.live()方法。使用.on()附加事件处理程序。旧版jQuery的用户应优先使用.delegate() .live()。

答案 1 :(得分:2)

$(“#tagWithHandlerOn”)。live(event,handler)可能就是这个伎俩