来自元素事件的Javascript调用函数没有全局范围 [英] Javascript call functions from element events without global scope

查看:98
本文介绍了来自元素事件的Javascript调用函数没有全局范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在外部加载的javascript文件(使用jQuery)中,我有:

In an externally loaded javascript file (using jQuery) I have:

$(function() {
    function foo() {
        console.log("bar");
    }
}

但是,当我尝试调用HTML时:

However in the HTML when I try and call:

<a onclick="foo()">Call foo</a>

这与Uncaught ReferenceError: foo is not defined分开.

是否可以将实际的函数调用保存在HTML (在a标记上)中,并且可以正常工作?

Is it possible keeping the actual function call in the HTML (on the a tag) and have it work?

推荐答案

是否可以将实际的函数调用保留在HTML中(在 标签),并且有效吗?

Is it possible keeping the actual function call in the HTML (on the a tag) and have it work?

否,如果您的函数foo不在全局范围内或不在某些特殊的全局对象之一上,则HTML无法找到您的函数,因此您无法在HTML中进行任何更改.作为参考,您的函数foo在本地范围内,而不在全局范围内.因此,要使HTML保持不变,您必须将foo移至全局范围或少数几个全局对象之一.

No, if your function foo is not in the global scope or on one of a few special global objects then the HTML cannot find your function and there is nothing you can do in the HTML to change that. For reference, your function foo is in a local scope, not in the global scope. So, for the HTML to remain unchanged, you would have to move foo to the global scope or to one of a few global objects.

有很多原因为什么直接在HTML中嵌入函数调用不是一个好习惯.一个主要原因是,它要求这些功能必须在全局范围内使用,这本身并不是一个好习惯.

There are a bunch of reasons why it is not a great practice to embed function calls directly in the HTML. One main reason is that it requires that those functions be globally scoped which, in itself, is not a good practice.

由于您已经在使用jQuery,因此只需将代码更改为此:

Since you already are using jQuery, you could simply change your code to this:

$(function() {
    function foo() {
        console.log("bar");
    }

    $("#callme").click(foo);
}

<a id="callme">Call foo</a>

或者,如果您有多个<a>标签希望具有相同的点击行为,则可以执行以下操作:

Or, if you have multiple <a> tags that want the same click behavior, you can do this:

$(function() {
    function foo() {
        console.log("bar");
    }

    $(".callme").click(foo);
}

<a class="callme">Call foo</a>
<a class="callme">Call foo</a>

或者,这些构造中的任何一个都可以使用匿名函数:

Or, either of these constructs could use an anonymous function:

$(function() {
    $(".callme").click(function(e) {
        console.log("bar");
    });
}

<a class="callme">Call foo</a>
<a class="callme">Call foo</a>


从实际HTML中删除所有代码引用被称为 Unobtrusive Javascript ,并且许多人认为这是一种好习惯.您可以在这里阅读有关该做法的信息:


Removing all code references from the actual HTML is referred to as Unobstrusive Javascript and is considered a good practice by many. You can read about that practice here:

什么是不引人注目的JavaScript及其重要性?

维基百科-不引人注目的JavaScript

W3-不干扰JavaScript的原理

这篇关于来自元素事件的Javascript调用函数没有全局范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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