javascript - Chrome Extension won't run function on button click -
I have this code on which you can scrap the HTML on the website you are on and copy it to the clipboard. I currently have a working version, when you click the Chrome icon, but I want to add many other options, so I'm trying to run a script by clicking the button under the extension popup.
Unfortunately, I can not manage to be something on the button click for my life! When I change my function with Alert ("Hi"), when clicking on the extension icon instead of the button inside the popup, this alert fades. I
document.addEventListener ('DOMContentLoaded', function () {document.getElementById ("full_team"). AddEventListener ('click', warning ("HI")) ;;}) & lt; Body & gt; & Lt; H2 & gt; Click to copy your roster & lt; / H2 & gt; & Lt; Button id = "full_tam" & gt; Full team & lt; / Button & gt; & Lt; Script src = "event.js" & gt; & Lt; / Script & gt; & Lt; / Body & gt;
addEventListener The name and function context of the event should be executed. However, the alert ("HI") does not reference the function; This statement implements the alertness, and returns undefined . There are two ways to solve this:
-
The small function can be executed, you can use the creation of anonymous functions. Statement
function () {alert ("HI"); } does not execute the alert, but returns the context of the function which is then applied when the warning is executed. Therefore, your code goes:
document.getElementById ("full_team"). AddEventListener ('click', function () {warning ("HI");}); -
Now create a named function for functions, or functions that can be reused:
function says () {warnings ( "HI"); } Again, it defines a function, but does not execute it. After that, you can use the name of the function:
document.getElementById ("full_team"). AddEventListener ('click', sayHi); Make sure to pass the context of the function, and do not execute it:
// Incorrect! Document.getElementById ("full_tem"). AddEventListener ('click', sayHi ());
Speaking of reuse work, assume that you want to create a parameter-dependent function. For example, suppose you want to be able to say "hello" on different elements, depending on which element is pressed.
Then, you can go to the higher-level and create a function that returns the function:
function says yes (name) {return function () {warning ("Hi," + name + "!"); }} Here, the function is right to implement: This function will return the document. GetElementById ("full_team"). AddEventListener ('click', sayHiTo ("Bob"));
Comments
Post a Comment