我有一个定义如下的函数:
window.onload = function() {
var ids = document.getElementById("idname");
function myFunction(){
/...*use ids var in here*./
}
}
我正在尝试从 html 中的按钮 onclick
调用 myFunction
:
<button onclick="myFunction();"></button>
但它说 myFunction
未定义。我明白,因为这是在 window.onload
内部。我怎样才能解决这个问题?我需要 window.onload
因为我需要使用 document.getElementById("testID")
来获取内容。
最佳答案
I need window.onload because I need to use document.getElementById("testID") to get content
不,您不需要window.onload
。您只需将代码放在文档中 ID 为 testID
的元素之后的某个位置即可。
示例:
<div id="testID"></div>
<script>
var ids = document.getElementById("testID");
function myFunction(){
/...*use ids var in here*./
}
</script>
但是,如果您想继续使用window.onload
,那么我建议不要使用内联事件处理程序,而是使用 JS 绑定(bind)处理程序:
window.onload = function() {
var ids = document.getElementById("testID");
ids.onclick = function(event){
/...*use ids var in here*./
}
};
(无论如何,这可能是一件好事)。
最后,您可以使用 this
或 event.target
获取对事件处理程序内元素的引用:
<div id="testID"></div>
<script>
document.getElementById("testID").onclick = function(event) {
// access element via `this` or `event.target`
};
</script>
关于javascript - 功能超出范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31276820/