Call JS function from HTML

六月ゝ 毕业季﹏ 提交于 2020-01-25 11:12:09

问题


I am unable to call a function from HTML file. This seems simple and my code matches what I've seen in similar SO answers, but I am missing something still. I know the JS is loading/running because the game in the canvas is working. Edit: Chrome console returns "testFunction is not defined" meaning the JS is NOT loaded. Why?

This is a test in the JS file:

function testFunction(){
    alert("It works!");
}

and it's called from the HTML like so:

<button type="button" onclick="testFunction()" id="testButton">Test</button>

Here's the JSFiddle http://jsfiddle.net/goldrunt/SeAGU/


回答1:


When using JSFiddle, your code is wrapped in an "onLoad" function (unless you specifically tell it otherwise).

Functions defined inside functions exist only in that function, so your testFunction, for example, is only accessible in the onLoad function that is your JS block of code. HTML from the outside can't access it.

Try changing "onLoad" to "no wrap - body" in the relevant option on JSFiddle.




回答2:


Unobtrusive JavaScript examples.

Javascript events

Like this using on + handler, is one way and most compatible.

HTML

<button type="button" id="testButton">Test</button>

Javascript

function testFunction() {
    alert("It works!");
}

window.onload = function () {
    document.getElementById('testButton').onclick = testFunction;
};

On jsFiddle

Or using the modern method EventTarget.addEventListener

Javascript

function testFunction() {
    alert("It works!");
}

window.addEventListener('load', function () {
    document.getElementById('testButton').addEventListener('click', testFunction, false);
}, false);

On jsFiddle

GlobalEventHandlers.onload



来源:https://stackoverflow.com/questions/21958028/call-js-function-from-html

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