未捕获的ReferenceError:函数未使用onclick定义

ECM*_*ipt 67 javascript onclick userscripts

我正在尝试为网站制作用户脚本以添加自定义表达.但是,我遇到了很多错误.

这是功能:

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.");
    }
}
Run Code Online (Sandbox Code Playgroud)

span标签的onclick调用该函数:

function appendEmote(em) {
    shoutdata.value += em;
}
Run Code Online (Sandbox Code Playgroud)

每次我单击一个具有onclick属性的按钮时,我都会收到此错误:

未捕获的ReferenceError:未定义函数.

任何帮助,将不胜感激.

谢谢!

更新

我试过用:

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);
Run Code Online (Sandbox Code Playgroud)

但是我收到了一个undefined错误.

这是脚本.

我试着这样做来测试听众是否有效并且不适合我:

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&amp;popup=true&amp;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);
Run Code Online (Sandbox Code Playgroud)

Bro*_*ams 111

永远不要使用用户.onclick()脚本或类似的属性!(这在常规网页中也很糟糕).

原因是用户脚本在沙箱中运行("孤立的世界"),并onclick在目标页面范围内操作,无法看到脚本创建的任何函数.

始终使用addEventListener()Doc(或等效的库函数,如jQuery .on()).

所以代替代码:

something.outerHTML += '<input onclick="resetEmotes()" id="btnsave" ...>'
Run Code Online (Sandbox Code Playgroud)


你会用:

something.outerHTML += '<input id="btnsave" ...>'

document.getElementById ("btnsave").addEventListener ("click", resetEmotes, false);
Run Code Online (Sandbox Code Playgroud)

对于循环,您无法将数据传递给类似的事件侦听器.请参阅doc.每当你改变innerHTML这种情况时,你就会破坏以前的事件听众!

如果不重构代码,可以使用数据属性传递数据.所以使用这样的代码:

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);
}
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)


警告:

  • 您的代码会为多个元素重用相同的ID.不要这样做,它是无效的.给定的ID每页只应出现一次.
  • 每次使用.outerHTML或时.innerHTML,您都会在受影响的节点上删除任何事件处理程序.如果您使用此方法,请注意这一事实.

  • 修复了我使用的:btnreset.onclick = function(){resetEmotes(); }; 谢谢! (2认同)
  • “从不”有点极端。看起来有点像 Evan You(vue 的创建者)宣称任何 Web 开发人员都不应该使用 input type=hidden。“最佳实践”是一回事……但是,规定任何人在任何情况下都不应使用[插入可能的技术或技术]的硬性规则很少是真实的。 (2认同)

小智 27

确定你是否使用了 Javascript 模块?!如果使用 js6 模块,您的 html 事件属性将不起作用。在这种情况下,您必须将函数从全局范围带到模块范围。只需将其添加到您的 javascript 文件中: window.functionName= functionName;

例子:

<h1 onClick="functionName">some thing</h1>
Run Code Online (Sandbox Code Playgroud)


小智 7

我认为你把函数放在 $(document).ready....... 函数总是在 $(document).ready....... 中提供。


Alf*_*bel 5

(click) = "someFuncionName()"我在特定组件的 .html 文件中以角度解决了这个问题。