2017-01-26 169 views
0

我遇到了全局變量問題,希望您能幫助我。javascript結果中的全局變量始終未定義

<li> 
<a href="<?php echo site_url("adminController/questionAdd/".$row->subjectid); ?>" id="<?php echo $row->subjectid; ?>" class="subject">Add Question</a> 
</li> 

現在從該行我在javascript通過我的ID在這條線由click()

$(document).ready(function() { 
     var correctAnswer; 
     var subId; 

     $(".subject").click(function() { 
      subId = ($(this).attr('id')); //passed the id variable into the global variable 
      alert(subId) // when I alert this it returns the value 
     }); 

現在我在這行中使用全局變量相同的$(document)。就緒(函數()

$('#form-user').submit(function(e){ 
       e.preventDefault(); 

       var me = $(this); 
       var correct = correctAnswer; 
       var passedSubId = subId; // passed the global variable to this local variable 
       console.log(correct); // this is okey 
       console.log(subId); // this is undefined 
}); 

結果

i 
undefined 
+0

你是否準確地關閉了「準備文檔」和「表單提交」? –

+0

謝謝你的迴應先生。是的,我正確關閉了它。 –

回答

0

您的代碼不會有任何效果。

你在那裏做什麼我認爲你點擊你的鏈接,然後你從頁面A移動到頁面B,並且你想使用你在頁面B的頁面A上設置的變量,抱歉,但是這會從不工作,當你刷新你的頁面時,你的整個腳本再次運行,它不知道你在前一頁做了什麼。 你將不得不任取該ID從URL(它的存在),或者其存儲例如在local storage,試試這個:

$(document).ready(function() { 
    var correctAnswer; 
    var subId; 

    $(".subject").click(function() { 
     subId = ($(this).attr('id')); //passed the id variable into the global variable 
     alert(subId) // when I alert this it returns the value 
     localStorage.setItem('subId', subId); 
     console.log('id stored'); 
    }); 

    $('#form-user').submit(function(e){ 
      e.preventDefault(); 

      var me = $(this); 
      var correct = correctAnswer; 
      var passedSubId = subId; // passed the global variable to this local variable 
      console.log(correct); // this is okey 
      console.log(subId); // this is undefined 

      storedSubId = localStorage.getItem('subId'); 
      alert(storedSubId); 
      console.log('stored id'); 
    }); 
}); 

反正得到它從URL絕對是你想要去的方式

+1

感謝您的迴應先生,這正是我的代碼問題。我上週已經修好了。但我真的很感謝你的迴應。非常感謝你。 –

1

您可以使用window來聲明全局變量,但建議不要使用h

可以聲明一個全局變量是這樣的:因爲你認爲它會

window.yourVariable = "something"; 
+0

感謝您的迴應,但我試過了,它不工作。 –

+0

@JohnHora您是否在創建警報的地方嘗試了'window.subId = subId'? –

+0

當我將我的全局變量聲明爲'windows.subId'時,會導致'Uncaught ReferenceError:subId is not defined'。 –