简体   繁体   English

我想在 onclick 上调用 function 但 function 应该在另一个 ZC1C424574AB11 内

[英]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.

相关问题 如何在onClick函数中编写JavaScript代码以及我也想调用另一个函数 - How can I write JavaScript code in onClick function as well as I also want to call another function 我想在div onClick函数中为图像禁用onClick事件? - I want to disabled onClick event for image inside div onClick function? 我想在变量中存储一个 function 并想在 onclick 事件中调用它 - I want to store a function in variable and want to call that at onclick event 如何在我的 React 组件中通过 onclick 在另一个 function 中调用一个 function? - How do I call a function inside another function through onclick in my React component? 在另一个函数中使用onclick() - Using onclick() inside another function 在另一个 function 内部调用 function - Call function inside of another function 我想将此随机函数更改为onclick函数 - I want to change this random function to onclick function 为什么在下面的代码片段中调用“onClick”的 function 应该在另一个箭头 function 内调用? - Why should the function which is called for 'onClick' here in this code snippet bellow should be called inside another arrow function? 从另一个函数调用一个函数内的一个函数 - call a function inside a function from another function 如果一个函数只在另一个函数中使用,我应该把它放在里面还是外面? - If a function is only used in another function should I keep it inside or outside it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM