javascript - Function out of scope? -
i have function defined follows:
window.onload = function() { var ids = document.getelementbyid("idname"); function myfunction(){ /...*use ids var in here*./ } } i trying call myfunction button onclick in html
<button onclick="myfunction();"></button> but says myfunction not defined. understand because inside window.onload. how can fix this? need window.onload because need use document.getelementbyid("testid") content
i need window.onload because need use document.getelementbyid("testid") content
no, don't need window.onload. have put code somewhere after element id testid in document.
example:
<div id="testid"></div> <script> var ids = document.getelementbyid("testid"); function myfunction(){ /...*use ids var in here*./ } </script> however, if want keep using window.onload, suggest not use inline event handlers, bind handler js:
window.onload = function() { var ids = document.getelementbyid("testid"); ids.onclick = function(event){ /...*use ids var in here*./ } }; (that might thing anyway).
lastly, can reference element inside event handler using this or event.target:
<div id="testid"></div> <script> document.getelementbyid("testid").onclick = function(event) { // access element via `this` or `event.target` }; </script>
Comments
Post a Comment