Uncaught ReferenceError: function is not defined with onclick

前端 未结 3 1154
陌清茗
陌清茗 2020-11-22 05:50

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:

fun         


        
3条回答
  •  时光说笑
    2020-11-22 06:20

    Never use .onclick(), or similar attributes from a userscript! (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.

    Always use addEventListener()Doc (or an equivalent library function, like jQuery .on()).

    So instead of code like:

    something.outerHTML += ''
    


    You would use:

    something.outerHTML += ''
    
    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!

    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  += ''
                                    + ''
                                    ;
        } 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:

    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.

提交回复
热议问题