Home > Article > Web Front-end > Why are my JavaScript functions not defined in JSFiddle?
Why JavaScript isn't Running on JSFiddle: Resolving Function Definition Errors
When attempting to run JavaScript code on JSFiddle, you may encounter errors indicating that specific functions are not defined. This occurs because JSFiddle encapsulates code within an onload function, limiting the scope of function definitions.
Function Definition and Referencing
In the provided code, functions such as fillList() and mySelectList() are defined within the window.onload function. This means that these functions are only accessible from within this function. However, you are trying to reference them as global variables in your HTML, leading to the errors.
Resolution Options
To resolve this, you have three options:
a) Modifying Functions as Global Variables
<code class="javascript">window.fillList = function() {}; // makes fillList a global function</code>
b) Unobtrusive JavaScript
<code class="javascript">// attach event listener from within JavaScript var mySelectList = document.getElementById('mySelectList'); mySelectList.addEventListener('change', function() { alert('Selection changed!'); });</code>
c) Modifying JSFiddle Settings
Recommendation
Option b) is highly recommended as it promotes best practices and code organization. By separating HTML from JavaScript, you gain greater control and flexibility over your code.
The above is the detailed content of Why are my JavaScript functions not defined in JSFiddle?. For more information, please follow other related articles on the PHP Chinese website!