jQuery extending jquery functions to dynamically loaded content

江枫思渺然 提交于 2019-12-01 11:14:52

问题


I'm having problems calling jQuery functions after replacing a div's content by using .html() and the .on() method. After I've visited a lot of pages I'm certain that the problem is caused by using the .on() method in a wrong way, but I can't figure out what's wrong. The problem is that the jQuery UI slider is not working after loading the html content. I think the solution could be quite simple, but I just can't find the correct answer while there are hundreds of people with a similar problem.

I'm using one div element as body to show the content of other div elements.

<body>

<a href="#" content="#div1">load content</a>

<div id="body">static content with working UI slider 
 <div class="slider"></div> 
</div> 

 <div id="div1">loaded content where the UI slider is not working
  <div class="slider"></div>
 </div>

</body>

I use this jQuery code to dynamically load the html content (and slider)

$(".slider").slider(); 

$("body").on("click", "a", function(event) {

event.preventDefault();

var htmlContent = $($(this).attr("content")).html();

$("div#body").html(htmlContent);


});

Code can be found on: http://jsfiddle.net/zTRFj/1/


回答1:


You're serializing the HTML, so the old elements are all destroyed then reconstructed in their new location.

Instead of calling .html() to get the HTML as a string, call .contents(). This'll return the actual elements, and will keep any bound events and references:

$(".slider").slider(); 

$("body").on("click", "a", function(event) {
    event.preventDefault();

    var htmlContent = $( $(this).attr("content") ).contents();

    $("div#body").html(htmlContent);
});


来源:https://stackoverflow.com/questions/14404725/jquery-extending-jquery-functions-to-dynamically-loaded-content

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