簡體   English   中英

Java全局變量在onsubmit事件處理程序中不可更改

[英]Javascript globals variables unchangeable in onsubmit event handler

我已經將onsubmit處理程序附加在這樣的表單標簽中:

<form action="file.php" method="post" onsubmit=" return get_prepared_build(this);" >

但是無論使用什么全局變量(當然,是在前面定義的),我都嘗試在get_prepared_build()函數內部進行更改-稍后它會不作修改。 看起來此函數處理了所有內容的本地副本,即使未保存文檔屬性值也是如此。

從標簽/屬性以這種方式調用javascript函數時,是否存在范圍/可見性問題?

這是函數:

function give_link(results)
{
    document.title = 'visibility test';
    return false;
}

然后在文件下面

<script>alert('test' + document.title );</script>

結果-在窗口中,我有一個新標題,但警報框顯示了舊的變量值。

要回答您的最后一個問題,不,從標記/屬性調用JavaScript函數時,沒有范圍/可見性問題:

<script type="text/javascript">
var x = 'Hello';
function get_prepared_build(f) {
    alert('Start get_prepared_build: x=' + x + '; document.cookie=' + document.cookie);
    x = 'There';
    // deliberately invalid cookie for test purposes only
    document.cookie = 'test';
    alert('End get_prepared_build: x=' + x + '; document.cookie=' + document.cookie);
    return false;
}
</script>
<form action="file.php" method="post" onsubmit="var ret=get_prepared_build(this);alert('Outside get_prepared_build: x=' + x + '; document.cookie=' + document.cookie);return ret;">
<input type="submit">
</form>

正如評論中提到的,演示您的特定問題的代碼示例將很有幫助。

編輯:在您的示例,更新document.title的函數永遠不會調用,或在您alert()當前值后調用,因此document.title似乎沒有改變。

<script type="text/javascript">
function changeDocumentTitle(f) {
    // this only runs onsubmit, so any alert()s at the bottom
    // of the page will show the original value before the
    // onsubmit handler fires
    document.title = 'new value';
    return false;
}
</script>
<form onsubmit="return changeDocumentTitle(this);">
<input type="submit">
</form>
<script type="text/javascript">
// this executes when the page loads, so it will show
// the value before any onsubmit events on the page fire
alert(document.title); // original value
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM