jQuery将jquery函数扩展到动态加载的内容 [英] jQuery extending jquery functions to dynamically loaded content
问题描述
使用.html()和.on()方法替换div的内容后,调用jQuery函数时遇到问题。
浏览了很多页面后,我确定问题是以错误的方式使用.on()方法引起的,但我无法弄清楚出了什么问题。问题是在加载html内容之后,jQuery UI滑块不起作用。我认为解决方案可能很简单,但是我找不到正确的答案,而有数百人遇到类似的问题。
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.
我正在使用一个div元素作为主体来显示其他div元素的内容。
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>
我使用这个jQuery代码动态加载html内容(和滑块)
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);
});
代码可以在以下位置找到: http://jsfiddle.net/zTRFj/1/
Code can be found on: http://jsfiddle.net/zTRFj/1/
推荐答案
你正在序列化HTML,所以旧的元素都被破坏,然后在新的位置被重建。
You're serializing the HTML, so the old elements are all destroyed then reconstructed in their new location.
而不是调用 .html()
将HTML作为字符串,调用 .contents()
。这将返回实际元素,并保留任何绑定的事件和引用:
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);
});
这篇关于jQuery将jquery函数扩展到动态加载的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!