【问题标题】:Uncaught ReferenceError: function is not defined with onclick未捕获的 ReferenceError:未使用 onclick 定义函数
【发布时间】:2013-06-27 00:33:43
【问题描述】:

我正在尝试为网站制作一个 userscript 以添加自定义表情。但是,我遇到了很多错误。

函数如下:

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.");
    }
}

span 标签的onclick 调用此函数:

function appendEmote(em) {
    shoutdata.value += em;
}

每次单击具有onclick 属性的按钮时,都会出现以下错误:

Uncaught ReferenceError: function is not defined.

更新

我尝试使用:

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);

但我收到了undefined 错误。

这里是script

我尝试这样做是为了测试听众是否工作,而他们不适合我:

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);

【问题讨论】:

  • 您的完整脚本的链接总是合适且值得赞赏的,除了应该在您的帖子中的相关代码 sn-ps。

标签: javascript onclick userscripts


【解决方案1】:

切勿使用.onclick(),或用户脚本中的类似属性!(它也是poor practice in a regular web page)。

原因是用户脚本在沙箱(“孤立世界”)中运行,而onclick 在目标页面范围内运行,无法看到您的脚本创建的任何功能。

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

所以不要像这样的代码:

something.outerHTML += '<input onclick="resetEmotes()" id="btnsave" ...>'


你会使用:

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

document.getElementById ("btnsave").addEventListener ("click", resetEmotes, false);

对于循环,您不能将数据传递给这样的事件侦听器,请参阅the 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);
}

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;
}


警告:

  • 您的代码对多个元素重复使用相同的 id。不要这样做,这是无效的。给定的 ID 每页只能出现一次。
  • 每次使用.outerHTML.innerHTML 时,都会丢弃受影响节点上的所有事件处理程序。如果您使用此方法,请注意这一事实。

【讨论】:

  • 我收到这个错误:Uncaught TypeError: Object 3 has no method 'addEventListener'
  • 那你做错了。链接到给出该错误的完整脚本,并链接到它运行的目标页面。
  • 修复了我使用的:btnreset.onclick = function(){ resetEmotes(); };谢谢!
  • 很高兴你得到它的工作,但该技术只能在某些条件下工作并且不可移植。
  • “从不”是一个极端。看起来有点像 Evan You(vue 的创建者)宣称任何 Web 开发人员都不应该使用 input type=hidden。 “最佳实践”是一回事……但规定任何人在任何情况下都不应使用 [insertPossibleTechniqueOrTechnology] 的硬性规定很少会成为现实。
【解决方案2】:

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

示例:

<h1 onClick="functionName">some thing</h1>

【讨论】:

    【解决方案3】:

    我想你把函数放在 $(document).ready....... 函数总是在 $(document).ready.......

    中提供

    【讨论】:

    • 我犯了同样的错误。你的回答解决了我的问题。
    • 为我工作!!!
    【解决方案4】:

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

    【讨论】:

      【解决方案5】:

      我在 Vue 中通过将我的 onclick="someFunction()" 切换为 @click="someFunction" 解决了这个问题。

      【讨论】:

      • 问题与Vue无关
      【解决方案6】:

      如果您使用的是外部 js 文件,请注意您的函数不在回调函数中。 删除回调函数就可以了

      (function() {  //comment this out
      
      //your code
      
      })(); //comment this out
      

      【讨论】:

        【解决方案7】:

        如果在html中使用该函数时未定义该函数,例如onclick = ‘function()’,则表示函数在回调中,在我的情况下是'DOMContentLoaded'。

        【讨论】:

        猜你喜欢
        • 2022-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多