我在尝试重置jQuery中的按钮事件内部的变量时遇到问题。该变量表示以div加载的页面。然后用setInterval函数刷新存储在变量中的页面的div元素。 这是代码:更新函数内部的变量JQuery
$(document).ready(function() {
var current_page="data.php"; //For update-the first page shown is data.php
//At startup
$("#content").load("/data.php",function(response){
//current_page="data.php"; The first command-current_page already set to "data.php"
if(response=="0"){
location.href="http://website.com";
}
});
//JS refresh timer
setInterval(function(){
alert(current_page); //Always shows 'data.php'->means it is not updated
if(current_page!="insert.php"){
$("#content").load("/"+current_page,function(response){
if(response=="0"){
location.href="http://website.com";
}
});
}
},5000); //5 seconds
//EVENTS
//Menu links pressed
$(".menu_link").click(function(){
var page=$(this).attr("data-page");
current_page=page; //Here it works.
$("#content").load("/"+page,function(response){
if(response=="0"){
location.href="http://website.com";
}
});
});
});
//Outside Jquery 'document'
//Select user button pressed
function loadData(){
var user_id=$("#menu_selector option:selected").val();
current_page="users.php?user_id="+user_id; //Not globally updated;inside function it is set.
$("#content").load("/users.php?user_id="+user_id,function(response){
if(response=="0"){
location.href="http://website.com";
}
});
}
我通过把在我的代码“警报”语句测试CURRENT_PAGE的价值。结论:在setInterval函数中,current_page变量始终设置为“data.php”。如果我删除第一行var current_page="data.php";
,则current_page为'未定义'。它看起来不是由loadData函数更新的。
我也试过在JQuery加载中移动loadData函数,但后来按钮找不到它(我用<button onclick="loadData();">Load page</button>
)
问题在哪里?
好像你已经作用域的变量的document.ready()函数...尝试在全球范围之外声明......权在脚本的顶部... – RohitS
是的..我已经修复了它。我看到了answear,并且我知道这个变量不仅仅是jQuery部分的全局变量。 –