簡體   English   中英

為什么這個javascript會拋出這個特殊錯誤?

[英]Why does this javascript throw this particular error?

在我的HTML代碼中,我有一個按鈕,按下時會運行一個javascript函數。 這是按鈕的HTML代碼:

<button type="button" onclick="repeatName()">Click me!</button>

我希望用戶在文本字段中輸入內容(在表單內部)。 這是文本字段的代碼:

<input type="text" name="txtName" />

我希望在按下按鈕后根據名稱文本框中輸入的信息更改div的innerHTML。 這是div的代碼:

<div name="editThis" width="50px" height="50px" border="1px">

</div>

單擊該按鈕時,我希望它運行下面的功能。 它應該改變div的innerHTML。

function repeatName() {
    var editField = document.getElementsByName("editThis").innerHTML;
    var repeatedName = document.theForm.txtName.value;

    editField = (repeatedName + " is the value.")

}

問題是,無論何時單擊按鈕,我都會在Firefox錯誤控制台中看到此錯誤:

Error: uncaught exception: [Exception... "Cannot modify properties of a WrappedNative"  nsresult: "0x80570034 (NS_ERROR_XPC_CANT_MODIFY_PROP_ON_WN)"  location: "JS frame :: chrome://global/content/bindings/autocomplete.xml :: onxblpopuphiding :: line 825"  data: no]

這個錯誤是什么?我該如何糾正?

根據文檔document.getElementsByName(str)返回“元素列表”。

很明顯,“元素列表”沒有單一的.innerHTML屬性。 我猜這個具體錯誤與你的瀏覽器內部機制有關,用於在自己的WrappedNative類型中表示該列表。

迭代結果; 在你的情況下,你只需要第一個結果,所以用數組訪問器語法[0]獲取它。

但是 ,由於name屬性與表單組件相關,因此您應該使用id 按ID檢索元素更容易,因為ID [應該]是唯一的。

此外,由於Javascript沒有引用,因此您無法將innerHTML存儲在變量中並更改它,期望原始屬性發生更改; 您必須在注釋innerHTML的同一語句中進行賦值:

function repeatName() {
    var editField = document.getElementsById("editField");
    var repeatedName = document.theForm.txtName.value;

    editField.innerHTML = repeatedName + " is the value."
}

我認為Tomalak是對的。 或者,您可以為div提供id,然后使用getElementById,它將返回單個對象而不是集合。

<div id="editThis" .... > .... </div>
...
...
document.getElementById("editThis").innerHTML = repeatedName + " is the value";

Div元素沒有name屬性,因此請使用id。

<div id="editThis" ...>

然后使用:

function repeatName() {
  var editField = document.getElementById("editThis");
  if (editField) {
    editField.innerHTML = document.theForm.txtName.value + ' is the value';
  }
}

為什么

[英]Why does <!— Not Throw a Syntax Error?

暫無
暫無

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

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