【问题标题】:Initialize Plugin after $.load( has changed the DOM在 $.load( 改变了 DOM 之后初始化插件
【发布时间】:2011-12-18 03:04:26
【问题描述】:
我有这样的东西,
$("a[rel^='prettyPhoto']").prettyPhoto({
theme: 'light_square'
});
但后来我使用$('.menu').click(function() { $('#content').load(page); });
如何在页面加载后初始化插件,以便它与已加载的新 html 一起使用?
谢谢
【问题讨论】:
标签:
javascript
jquery
events
bind
live
【解决方案1】:
jquery document.ready 在 DOM 完全加载时执行
http://api.jquery.com/ready/
例子
$(function(){
//Whatever code you want to execute after the page is loaded
})
如果您想将函数附加到使用 ajax 加载到 DOM 的元素上,您可以根据您的 jquery 版本使用 live 或 on
如果您使用低于 1.7 的 jquery 版本,请使用 live
$('.menu').live("click",function(){
//Do whatever you want
});
如果您使用 jquery 1.7 或 +,请使用 on
$('body').on("click",".menu",function(){
//do whatever you want
});
【解决方案2】:
.load() 将回调作为页面加载时触发的第二个参数:
$('.menu').click(function() {
$('#content').load(page, function() {
$("a[rel^='prettyPhoto']").prettyPhoto({
theme: 'light_square'
});
});
});