问题
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