2009-12-25 93 views
0

我有以下幾點:jquery.val()在頁面上工作,關閉頁面不?爲什麼?

<script type="text/javascript"> 
var noteid = $('#noteid').val(); 
</script> 
<input type="hidden" name="noteid" id="noteid" value="321"> 

這個偉大的工程......但現在我想移動的JavaScript後的頁面到鏈接JS文件,像這樣:

<script type="text/javascript" src="/js/note_beta.js"> </script> 
<input type="hidden" name="noteid" id="noteid" value="321"> 

此分機JS文件的代碼是:「var noteid = $('#noteid')。val();」但它不工作......當它不在頁面本身上時,有沒有一種方法可以讓它工作?

感謝

回答

8

嘗試在(document).ready函數,這確保它不會運行,直到頁面加載包裝jQuery代碼,你不跑的努力,他們之前引用元素的風險被添加到DOM

因此改變:

var noteid = $('#noteid').val(); 

要這樣:

var noteid; // define it up here to ensure scope is done properly 
$(document).ready(function() { 
    noteid = $('#noteid').val(); 
}); 
+0

你打我30秒:) +1更快更細緻。 – 2009-12-25 17:41:16

1

嘗試包裝你這樣的代碼,所以它不會繼續運行,直到頁面加載

$(document).ready(function(){ 
    var noteid = $('#noteid').val(); 
}); 
1

除了$(文件)。就緒,永遠不要給一個JavaScript變量同名命名元素(通常會提供輸入)。這種情況可能沒有什麼不同,但它可能導致錯誤。 Check out this article on the scope chain在底部的更多信息。這可以輕鬆地咬你。

編輯:文章的簡短版本是將名稱元素添加到作用域鏈,所以如果JavaScript正在尋找屬性.noteid,它將使用input.noteid而不是window.noteid(window.noteid = =聲明爲全局變量時的var noteid。)

相關問題