Bind an event handler on a element who's inserted by the jQuery .html() function

半城伤御伤魂 提交于 2019-12-01 08:03:15

问题


I render some new content with .html() after ajax call into my site.

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

Now. How can I bind an event handler to div tags in that replaced html without including the script again? now the html the I render into my site looks like this:

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

I want to get rid of the <script> Tag because it's e redeclaration and if I load the same content into that tag again 2 scripts gonna be loaded. Any hint?


回答1:


Try using jQuery.live()


As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().




回答2:


$("#tagWithHandlerOn").live(event,handler) might just do the trick



来源:https://stackoverflow.com/questions/5003747/bind-an-event-handler-on-a-element-whos-inserted-by-the-jquery-html-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!