我有一个没有页面更改的HTML网站.它只是使用ajax调用将不同的元素加载到页面上的每个位置.我需要登录函数在第一次加载页面后运行(因为它需要索引上的元素存在),但是当我使用$(document).ready(login)时,每次加载一个元素时它都会触发(因为它将元素加载到页面上,它会陷入无限循环中).除了将它放在我的索引页面的底部(这看起来非常脆弱)之外,是否有一种方法可以在索引页面加载完成后加载它,但是每次ajax请求都会向页面添加内容时不会运行它?
我的登录功能如下所示:
function login ()
{
if($.cookie('employee'))
employee = $.cookie('employee');
if(employee && !employee.login)
$("div.middle").load('login.html');
else
$("div.middle").load('main.html');
}
function logout ()
{
//FIXME send a logout request to server to end session also
employee = null;
$.cookie('employee', null);
$("div.middle").load('login.html');
}
Run Code Online (Sandbox Code Playgroud)
我的初始就绪函数如下所示://全局变量var employee = new Object;
$(document).ready(function(){
$("div.leftColumn").html(buildLeftNav());
//set height of middle if height of leftColumn is less than height of middle
if($("div.leftColumn").css('height') < $("div.middle").css('height'))
$("div.center").css('height' , $('div.middle').css('height'));
//handle login and logout
$.cookie.json = true;
login();
});
Run Code Online (Sandbox Code Playgroud)
我已经设置了一个小提琴来说明:http://jsfiddle.net/uZVP4/
您的问题可能不在于,document.ready但您可能会在AJAX调用中反复加载相同的脚本.由于脚本会自动加载新内容,因此它会创建无限循环的加载新内容,从而导致新内容再次加载.反复出现.
如果必须将脚本保存在远程页面中,则可以使用$.get不会在ajax内容中执行脚本的脚本