Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
555 views
in Technique[技术] by (71.8m points)

javascript - 未捕获的ReferenceError:函数未使用onclick定义(Uncaught ReferenceError: function is not defined with onclick)

I'm trying to make a userscript for 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("
");
    EmoteURLLines = EmoteURL.value.split("
");
    EmoteUsageLines = EmoteUsage.value.split("
");

    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&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);
  ask by ECMAScript translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Never use .onclick() , or similar attributes from a userscript!

(切勿使用.onclick()或用户.onclick()类似属性!)

(It's also poor practice in a regular web page ).

((这在常规网页中也很糟糕 )。)

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 .

(对于循环,您无法将数据传递给类似的事件侦听器。请参阅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.

    (您的代码会为多个元素重用相同的ID。)

    Don't do this, it's invalid.

    (不要这样做,它是无效的。)

    A given ID should occur only once per page.

    (给定的ID每页只应出现一次。)

  • Every time you use .outerHTML or .innerHTML , you trash any event handlers on the affected nodes.

    (每次使用.outerHTML.innerHTML ,都会在受影响的节点上.outerHTML任何事件处理程序。)

    If you use this method beware of that fact.

    (如果您使用此方法,请注意这一事实。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...