简体   繁体   中英

How to call a function in JavaScript with onclick event

I am creating a Google Chrome Extension, and I'm trying to make a button that opens up a stored random website in a new tab once clicked. I've scoured this website and tried everything to no avail. I'm sure it's something simple that I'm missing.

I know the random website function itself works, as I initially had it as a context menu function where it worked fine. However, now that I've attempted to make it a button, it doesn't seem to work.

In randomSiteTestScript.js :

var links = [multiple hhtp:// links]

document.getElementById("randomsite").addEventListener("click", openSite);

function openSite() {
    code that works
};

In popup.html :

<p><button id="randomsite">Click for random site!</button></p>
<script src="randomSiteTestScript.js"></script>

Once the button is clicked, absolutely nothing happens. I'm not getting any errors, but nothing is happening. Again, I know the openSite function works properly as I changed nothing since moving from a context menu functionality. I don't believe the function is being called at all. Thanks in advance for any help!

No need for a event listener here... just use an inline onclick event handler.

<button id="randomsite" onclick="openSite(links[Math.floor(Math.random()*links.length)]);">Click for random site!</button>

Pass the URL to OpeSite(URL) and process the opening from there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM