问题
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