我正在学习 JavaScript,在这个脚本中,我尝试通过单击按钮插入一个简单的文本行。我尝试了两种方法,但都给出了错误。
<input type="button" value="getValue" id="getValue" />
<div id="rowgen"></div>
(function(){
window.onload = function() {
// Code to display a google map on page
//...
document.getElementById("getValue").onclick = function(){
document.getElementById.innerHTML('rowgen') += '<p>Hello world</p>';
};
}
})();
我收到错误:
Uncaught ReferenceError: Invalid left-hand side in assignment
对于线路
document.getElementById.innerHTML('rowgen') += '<p>Hello world</p>';
对于第二种方法,我尝试过:
<input type="button" value="getValues" id="getValues" onclick="genRow()"/>
<div id="rowgen"></div>
(function(){
window.onload = function() {
// Code to display a google map on page
//...
function genRow(){
document.getElementById.innerHTML('rowgen') += '<p>Hello world</p>';
}
}
})();
这次我在 HTML 文件中收到错误:
Uncaught ReferenceError: genRow is not defined
上线
<input type="button" value="getValues" id="getValues" onclick="genRow()"/>
最佳答案
genRow
需要位于 onload
block 之外。当您调用它时它还不存在。
此外,您的 getElementById
调用已修复如下:
function genRow(){
document.getElementById('rowgen').innerHTML += '<p>Hello world</p>';
}
(function(){
window.onload = function() {
// Code to display a google map on page
//...
}
})();
关于尝试在按钮单击时添加 innerhtml 时出现 JavaScript 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21210225/