我有一个问题,我用 javascript 编写的程序中的函数有问题。
当您单击一个段落时,该函数应该可以工作,但是当我单击时,javascript 控制台会抛出以下错误:“ Uncaught ReferenceError :donethingy 未定义 线:1"。
JS:
window.onload = function(){
var thy = document.getElementById("thy");
var commanderIssue = document.getElementById("commanderIssue");
var listado = document.getElementById("thaCosa");
var thyLy = document.getElementsByTagName("p");
var nli;
var thyText;
var inserting = "a";
var commander = "b";
thy.onclick = function(){
inserting = "* " + prompt("Create a new item");
nli = document.createElement("p");
thyText = document.createTextNode(inserting);
nli.appendChild(thyText);
listado.appendChild(nli);
thyLy = document.getElementsByTagName("p");
}
thyLy.onclick = function donethingy(){
// thyLy.textDecoration.overline;
alert("done");
}
commanderIssue.onclick = function(){
alert("this thing is");
}
}
最佳答案
根据您使用的语法,名称 donethingy
实际上不会成为函数的名称,因为您将函数的代码直接分配给 onclick
属性thyLy
。
你可以这样做:
// This is a function declaration that associates a name with the function
function donethingy(){
// thyLy.textDecoration.overline;
alert("done");
}
// Then the function can be referred to or invoked by name
thyLy.onclick = donethingy;
但是,当您在一条语句中创建并分配该函数时,该函数实际上会变成匿名的,因为它是通过您分配给它的属性来存储和访问的。
决定创建函数声明还是匿名函数需要考虑以下因素:
- 匿名函数不易重用。
- 匿名函数不容易进行单元测试。
- 命名函数可能需要更多内存,但可以重复使用并且可以 易于进行单元测试。
关于javascript - 为什么我的函数 "donethingy"被视为 "not declared"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42376129/