How can i execute a javascript when a user clicks a button

落爺英雄遲暮 提交于 2019-12-25 04:44:22

问题


I am creating an extension for Chrome. I want to execute a script when the user clicks a button. Here is the code i currently have in my html file

<input type="button" id ="button" onclick='notEmpty()' value="Play"/>

The notEmpty() is in a javascript (.js) file. How can I execute another script in the notEmpty() function?


回答1:


If you want to use functions that are located in another file, you would need to import those files:

<script type="text/javascript" src="/path/to/script.js"></script>

But, in Google Chrome Extensions, if you want to "execute" a script when you click on a button (from an extension page), you can use the chrome.tabs.executeScript functionality

// Run that script on the current tab. The first argument is the tab id.
chrome.tabs.executeScript(null, {file: '/path/to/script.js'});

It all depends on your scenario, when you "executeScript" as shown above, it will inject a content script into that DOM. If you import that script, you will just use those functionality in the current DOM (in that case the extension page, not the tab).

Hope that helped!




回答2:


I have not written an extension for chrome but for typical javascript you can do one of the following.

<script type="text\javascript">
   function notEmpty()
   {
       someOtherFunction();
   }
</script>

or

<input type="button" id ="button" onclick='notEmpty(); someOtherFunction();' value="Play"/>


来源:https://stackoverflow.com/questions/4549690/how-can-i-execute-a-javascript-when-a-user-clicks-a-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!