从html调用函数内部的JavaScript函数 [英] Calling JavaScript function that is inside a function from html

查看:93
本文介绍了从html调用函数内部的JavaScript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在嵌套函数方面有些挣扎.问题,我想从HTML调用函数,但是我所有的JavaScript都坐在里面等待DOM加载的函数.

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.

如果我要从DOM加载的函数中调用要调用的函数,则无法从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.

推荐答案

大概当您说从[您的] HTML调用函数"时,您的意思是:

Presumably when you say you "call a function from [your] HTML" you mean:

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

...或类似的

这是不使用 onxyz -属性样式的事件处理程序的众多原因之一:如果它们是全局函数,则只能调用自己的函数.

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.

相反,如果需要支持过时的Microsoft浏览器,请使用现代事件处理技术(例如 addEventListener (或 attachEvent )连接处理程序;如果这样做,请此处的我的答案具有您可以使用的跨浏览器功能).如果这样做,则可以在代码范围内使用任何函数范围内的代码进行连接,而不再需要是全局的.

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). 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.

简单的例子:

(function() {
  // Not global
  function fooClick() {
    console.log(".foo clicked");
  }
  
  // Hook it up
  document.querySelector(".foo").addEventListener("click", fooClick);
})();

<div class="foo">Click me</div>

这篇关于从html调用函数内部的JavaScript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆