我在嘗試重置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部分的全局變量。 –