javascript 未捕获的 ReferenceError:未使用 onclick 定义函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17378199/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Uncaught ReferenceError: function is not defined with onclick
提问by ECMAScript
I'm trying to make a userscriptfor a website to add custom emotes. However, I've been getting a lot of errors.
我正在尝试为网站制作用户脚本以添加自定义表情。但是,我遇到了很多错误。
Here is the function:
这是函数:
function saveEmotes() {
removeLineBreaks();
EmoteNameLines = EmoteName.value.split("\n");
EmoteURLLines = EmoteURL.value.split("\n");
EmoteUsageLines = EmoteUsage.value.split("\n");
if (EmoteNameLines.length == EmoteURLLines.length && EmoteURLLines.length == EmoteUsageLines.length) {
for (i = 0; i < EmoteURLLines.length; i++) {
if (checkIMG(EmoteURLLines[i])) {
localStorage.setItem("nameEmotes", JSON.stringify(EmoteNameLines));
localStorage.setItem("urlEmotes", JSON.stringify(EmoteURLLines));
localStorage.setItem("usageEmotes", JSON.stringify(EmoteUsageLines));
if (i == 0) {
console.log(resetSlot());
}
emoteTab[2].innerHTML += '<span style="cursor:pointer;" onclick="appendEmote(\'' + EmoteUsageLines[i] + '\')"><img src="' + EmoteURLLines[i] + '" /></span>';
} else {
alert("The maximum emote(" + EmoteNameLines[i] + ") size is (36x36)");
}
}
} else {
alert("You have an unbalanced amount of emote parameters.");
}
}
The span
tag's onclick
calls this function:
该span
标签的onclick
调用该函数:
function appendEmote(em) {
shoutdata.value += em;
}
Every time I click a button that has an onclick
attribute, I get this error:
每次单击具有onclick
属性的按钮时,都会收到此错误:
Uncaught ReferenceError: function is not defined.
未捕获的 ReferenceError:未定义函数。
Any help would be appreciated.
任何帮助,将不胜感激。
Thank you!
谢谢!
Update
更新
I tried using:
我尝试使用:
emoteTab[2].innerHTML += '<span style="cursor:pointer;" id="'+ EmoteNameLines[i] +'"><img src="' + EmoteURLLines[i] + '" /></span>';
document.getElementById(EmoteNameLines[i]).addEventListener("click", appendEmote(EmoteUsageLines[i]), false);
But I got an undefined
error.
但我有一个undefined
错误。
Here is the script.
这是脚本。
I tried doing this to test if listeners work and they don't for me:
我尝试这样做是为了测试听众是否有效而他们对我无效:
emoteTab[2].innerHTML = '<td class="trow1" width="12%" align="center"><a id="togglemenu" style="cursor: pointer;">Custom Icons</a></br><a style="cursor: pointer;" id="smilies" onclick=\'window.open("misc.php?action=smilies&popup=true&editor=clickableEditor","Smilies","scrollbars=yes, menubar=no,width=460,height=360,toolbar=no");\' original-title="">Smilies</a><br><a style="cursor: pointer;" onclick=\'window.open("shoutbox.php","Shoutbox","scrollbars=yes, menubar=no,width=825,height=449,toolbar=no");\' original-title="">Popup</a></td></br>';
document.getElementById("togglemenu").addEventListener("click", changedisplay,false);
回答by Brock Adams
Never use .onclick()
, or similar attributes from a userscript!(It's also poor practice in a regular web page).
切勿使用.onclick()
, 或来自用户脚本的类似属性!(在常规网页中这也是不好的做法)。
The reason is that userscripts operate in a sandbox ("isolated world"), and onclick
operates in the target-page scope and cannot see any functions your script creates.
原因是用户脚本在沙箱(“孤立世界”)中onclick
运行,并在目标页面范围内运行,无法看到您的脚本创建的任何函数。
Always use addEventListener()
Doc(or an equivalent library function, like jQuery .on()).
始终使用addEventListener()
Doc(或等效的库函数,如 jQuery .on())。
So instead of code like:
所以,而不是像这样的代码:
something.outerHTML += '<input onclick="resetEmotes()" id="btnsave" ...>'
You would use:
你会使用:
something.outerHTML += '<input id="btnsave" ...>'
document.getElementById ("btnsave").addEventListener ("click", resetEmotes, false);
For the loop, you can't pass data to an event listener like that See the doc. Plus every time you change innerHTML
like that, you destroy the previous event listeners!
对于循环,您不能将数据传递给这样的事件侦听器,请参阅文档。另外,每次innerHTML
这样更改时,都会破坏以前的事件侦听器!
Without refactoring your code much, you can pass data with data attributes. So use code like this:
无需大量重构代码,您就可以传递带有数据属性的数据。所以使用这样的代码:
for (i = 0; i < EmoteURLLines.length; i++) {
if (checkIMG (EmoteURLLines[i])) {
localStorage.setItem ("nameEmotes", JSON.stringify (EmoteNameLines));
localStorage.setItem ("urlEmotes", JSON.stringify (EmoteURLLines));
localStorage.setItem ("usageEmotes", JSON.stringify (EmoteUsageLines));
if (i == 0) {
console.log (resetSlot ());
}
emoteTab[2].innerHTML += '<span style="cursor:pointer;" id="'
+ EmoteNameLines[i]
+ '" data-usage="' + EmoteUsageLines[i] + '">'
+ '<img src="' + EmoteURLLines[i] + '" /></span>'
;
} else {
alert ("The maximum emote (" + EmoteNameLines[i] + ") size is (36x36)");
}
}
//-- Only add events when innerHTML overwrites are done.
var targetSpans = emoteTab[2].querySelectorAll ("span[data-usage]");
for (var J in targetSpans) {
targetSpans[J].addEventListener ("click", appendEmote, false);
}
Where appendEmote is like:
其中 appendEmote 就像:
function appendEmote (zEvent) {
//-- this and the parameter are special in event handlers. see the linked doc.
var emoteUsage = this.getAttribute ("data-usage");
shoutdata.value += emoteUsage;
}
WARNINGS:
警告:
- Your code reuses the same id for several elements. Don't do this, it's invalid. A given ID should occur only once per page.
- Every time you use
.outerHTML
or.innerHTML
, you trash any event handlers on the affected nodes. If you use this method beware of that fact.
- 您的代码对多个元素重复使用相同的 id。不要这样做,这是无效的。给定的 ID 应该每页只出现一次。
- 每次使用
.outerHTML
或 时.innerHTML
,都会丢弃受影响节点上的所有事件处理程序。如果您使用此方法,请注意这一事实。
回答by nbixler
I was receiving the error (I'm using Vue) and I switched my onclick="someFunction()"
to @click="someFunction"
and now they are working.
我收到错误消息(我正在使用 Vue),然后我切换onclick="someFunction()"
到了@click="someFunction"
,现在它们正在工作。