简体   繁体   English

从html调用函数内部的JavaScript函数

[英]Calling JavaScript function that is inside a function from html

Struggling a bit with nested functions. 嵌套函数有点挣扎。 Problem, I want to call a function from my HTML, but all my JavaScript sits inside to wait for the DOM loaded function. 问题,我想从HTML调用函数,但是我所有的JavaScript都坐在里面等待DOM加载的函数。

If I take the function I want to call out of the DOM loaded function, I can not access the variables from inside the DOM loaded function. 如果我要从DOM加载的函数中调用要调用的函数,则无法从DOM加载的函数内部访问变量。

Presumably when you say you "call a function from [your] HTML" you mean: 大概当您说“从[您的] HTML调用函数”时,您的意思是:

<div onclick="yourFunction()">...</div>

...or similar. ...或类似。

This is one of the many reasons not to use onxyz -attribute-style event handlers: You can only call your own functions if they're globals. 这是不使用onxyz -attribute风格的事件处理程序的众多原因之一:您只能调用自己的函数(如果它们是全局函数)。

Instead, hook up the handlers with modern event handling techniques, such as addEventListener (or attachEvent if you need to support obsolete Microsoft browsers; if you do, my answer here has a cross-browser function you can use). 相反,请使用现代事件处理技术(例如addEventListener (如果需要支持过时的Microsoft浏览器,则可以attachEvent如果需要,请使用attachEvent ;如果这样做, 我的答案是可以使用的跨浏览器功能))来连接处理程序。 If you do that, you can use any function in-scope of your code doing the hookup, it doesn't need to be a global anymore. 如果这样做,则可以在代码范围内使用任何函数范围内的代码进行连接,而不必再成为全局函数。

Simple example: 简单的例子:

 (function() { // Not global function fooClick() { console.log(".foo clicked"); } // Hook it up document.querySelector(".foo").addEventListener("click", fooClick); })(); 
 <div class="foo">Click me</div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM