为什么这个javascript会抛出这个特定的错误?
在我的HTML代码中,我有一个按钮,按下该按钮时运行javascript函数。这是按钮的HTML代码:为什么这个javascript会抛出这个特定的错误?,javascript,html,Javascript,Html,在我的HTML代码中,我有一个按钮,按下该按钮时运行javascript函数。这是按钮的HTML代码: <button type="button" onclick="repeatName()">Click me!</button> 问题是,每当单击按钮时,我都会在Firefox错误控制台中看到此错误: Error: uncaught exception: [Exception... "Cannot modify properties of a WrappedNative
<button type="button" onclick="repeatName()">Click me!</button>
问题是,每当单击按钮时,我都会在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]
这个错误是什么?如何更正它?根据,文档。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."
}
我认为托马拉克是对的。或者,您可以给div一个id,然后使用getElementById,它将返回单个对象而不是集合 i、 e
。。。。
...
...
document.getElementById(“editThis”).innerHTML=repeatedName+“是值”;
Div元素没有name属性,因此请使用id
<div id="editThis" ...>
此外,这只会更改变量
editField
,但不会更改editThis
的innerHTML
。当您/他设置editField的值时会发生什么情况…这不会更改元素的innerHTML。需要说editField=document.getElementsByName(“editThis”)[0]
然后是editField.innerHTML=…
而不是editField=…
参考标准要比社区wiki好得多。@RobG:在实用、易读和可靠的文档方面,它的效果差不多。如果你能提出一个替代方案,那就去做吧。
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]
function repeatName() {
var editField = document.getElementsById("editField");
var repeatedName = document.theForm.txtName.value;
editField.innerHTML = repeatedName + " is the value."
}
<div id="editThis" .... > .... </div>
...
...
document.getElementById("editThis").innerHTML = repeatedName + " is the value";
<div id="editThis" ...>
function repeatName() {
var editField = document.getElementById("editThis");
if (editField) {
editField.innerHTML = document.theForm.txtName.value + ' is the value';
}
}