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関数によって更新されていないようです。
また、loadData関数をJQueryの読み込み内に移動してみましたが、ボタンが見つからない(<button onclick="loadData();">Load page</button>
を使用)
問題はどこですか?
は思わ:だからではなく、名前空間を作成するか、他の私はjqueryのコード外の宣言を移動しましたあなたのスクリプトの先頭に... – RohitS
はい..私はすでにそれを修正しました。私はその答えを見ました。変数がjqueryの部分だけにグローバルではないことは分かっていました。 –