[英]I want to call a function on onclick but that function should be inside another function
Javascript code: Javascript 代码:
function abc() {
function def() {
//do something
}
}
HTML code: HTML 代码:
<button onclick="def()">click me</button>
I get the error def() is not defined
.我得到错误
def() is not defined
。
Try this.尝试这个。
function def(){
//do something
}
function abc(playDef){
if(playDef){
def()
}
}
<button onclick="def(true)">click me</button>
For more functions you can pass arguments and manage if condition对于更多功能,您可以通过 arguments 并管理 if 条件
You only need to declare def in global scope:只需要在全局 scope 中声明 def:
function abc(){
window.def = function(){
console.log("hello, I'm function def");
}
}
abc();
def();
But remember you need to call abc first to get access to def function.但请记住,您需要先调用 abc 才能访问 def function。 Hope this helps.
希望这可以帮助。 Good luck.
祝你好运。
I have completed my answer with a code snippet, you can try the working solution:我已经用代码片段完成了我的答案,您可以尝试工作解决方案:
function abc(){ window.def = function(){ console.log("hello, I'm function def"); } } abc();
<button onclick='def();'>Click Me!</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.