在javascript中添加多个事件监听器到元素 [英] Adding multiple event listeners in javascript to element

查看:150
本文介绍了在javascript中添加多个事件监听器到元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小的拖放设置并运行,但它使用内联JavaScript,我更喜欢将其全部移动到外部文件。理论上这是一个很容易的交换,但我在检查员中得到了参考错误,我的小型化失败了。

I've got a small drag and drop set up up and running, but it's using inline javascript and I'd prefer to move it all to an external file. Theoretically it's an easy swap, but I'm getting referenceErrors in my inspector and my minifcation is failing.

从我可以看出,问题来自于 return

From what I can tell, the issue is coming from the return.

原始HTML

<section id="titles" ondrop="dropClip(this, event)" ondragenter="return false" ondragover="return false"></section>

所需的HTML

<section id="titles"></section>

JavaScript

JavaScript

var titles = document.getElementById('titles');

titles
    .addEventListener('drop', dropClip(this, event))
    .addEventListener('dragenter', return false)
    .addEventListener('dragover', return false);


推荐答案

Javascript是一种语言,其功能是一流的对象。这意味着,可能与您可能遇到的其他编程语言相反,您可以像任何其他对象一样处理函数:您可以传递它,您可以返回它,您可以在其中具有函数内部的函数功能在其中,等等。

Javascript is a language where functions are "first-class objects". This means, possibly contrary to other programming languages that you may have experience in, that you can treat a function like any other object: you can pass it around, you can return it, you can have a function with a function inside it with a function inside it, and so on.

这样做的结果可能是一个非常意想不到的编程风格,需要在Javascript中成功。在其他语言中,UI事件绑定以各种方式发生(例如C#的 Button1.Click + = new System.EventHandler(this.myEventHandler); 或Classic VB's Button_Click())。在C#中,您可以传递代理,这些特定对象具有一组特定的参数和返回值,函数可以绑定到该对象。但是,所有这些都会在javascript中消失,因为您可以直接将功能附加到属性 。对于浏览器DOM事件处理,该属性被认为是一个函数引用,并且在该事件的本机事件处理代码期间,它调用与该事件具有相同名称的属性附加的函数。

The consequence of this may be a very unexpected programming style required to be successful in Javascript. In other languages, UI event binding occurs in a variety of ways (such as C#'s Button1.Click += new System.EventHandler(this.myEventHandler);, or Classic VB's Button_Click()). In C#, you can pass around delegates, which are special objects with a specifically defined set of parameters and return values, to which a function can be bound. But all that disappears in javascript because you can simply attach a function to a property directly. For browser DOM event handling, the property is assumed to be a function reference, and during the native event handling code for that event, it calls the function attached to the property with the same name as the event.

好的,你说,我们有功能。我们可以把它们传递给他们,像变量一样对待它们。现在是什么?

Okay, you say, we have functions. And we can pass them around and treat them just like variables. Now what?

首先,请特别注意以下两个函数声明与相同。它们产生完全相同的结果,在当前作用域中声明一个名为 myfun 的函数(在浏览器中,窗口对象或正在运行的当前函数)

First, please take special note that the following two functions declarations are identical. They yield the exact same result, of declaring a function named myfun in the current scope (in a browser, the window object or the current function that is running).

function myfun(param1, param2) {
   //do some stuff
};

var myfun = function (param1, param2) {
   //do some stuff
};

实际上,第一个最终会得到一个名称属性,第二个不会,可能还有一些其他微小的差异,但所有实践意图和目的他们是相同的)。

(Actually, the first one will end up with a name property that the second one won't, and possibly some other minor differences, but for all practical intents and purposes they are identical).

第一个只是第二个的快捷方式。基本上,您创建一个函数(可能有也可能没有名称)并将其分配给一个变量。程序员使用调用结果 myfun 函数的方便快捷方式,但实际情况是 myfun 变量 - 它现在包含一个特定的函数。

The first one is just a shortcut for the second one. Basically, you create a function (that may or may not have a name) and assign it to a variable. Programmers use the convenient shortcut of calling the result "the myfun function", but in reality the case is "the myfun variable--which contains a particular function right now".

您可以获得许多对同一个函数的引用 - 这是一个真实的对象 - 只需将它分配给其他变量:

You can get many references to the same function--which is a true object--just by assigning it to other variables:

function myfun(param1, param2) {
   //do some stuff
};

var a = myfun, b = myfun, c = myfun;

a(); // runs `myfun`
b(); // runs `myfun`
c(); // runs `myfun`

接下来要注意的是,要调用一个函数,你必须使用括号后面的括号括起来。

The next thing to notice is that to invoke a function, you must use parentheses after its name, and any parameters go inside the parentheses.

var result = myfun('a', 1); // invoke the `myfun` function
   // and store its return value in variable `result`

但是,请回顾我们的任务声明,使 a b c 都是 myfun 函数的别名:在这些情况下,我们没有使用括号,因为 - 这里是真的很重要,所以要注意

But take a look back at our assignment statement making a, b, and c all be aliases of the myfun function: in those cases we didn't use parentheses, because--and here is where it gets really important, so pay attention:


要调用一个函数(并获取函数的返回值),在其名称后面使用括号。

To invoke a function (and get the function's return value), use parentheses after its name.

要传递函数引用,请不要使用括号。

To pass a function reference, do not use parentheses.

如果我们这样做了:

var a = myfun(), b = myfun(), c = myfun();

a b c 将不再是指向 myfun 函数的指针。他们都将是 myfun 结果,并且将包含返回的任何 myfun 未定义如果没有返回任何内容。如果您尝试调用其中一个,请说 a(),您将收到类似于以下错误的错误:

a, b, and c would no longer be pointers to the myfun function. They would all be the result of myfun and would contain whatever myfun returned--or undefined if it didn't return anything. If you tried to invoke one of these, say a() you would get some error similar to:

> TypeError: a is not a function

现在我已经画了所有的背景,有一个简单要知道这将使您在 addEventListener 成功的轨道上:它期望一个函数作为第二个参数。在你的示例代码中,当addEventListener调用它们时,你已经放置了要运行的函数的内容,但没有实际的函数。

Now that I've painted all that background, there is one simple thing to know that will get you on track to being successful with addEventListener: it expects a function as the second parameter. In your example code, you've put the contents of functions you'd like to run when addEventListener calls them, but no actual functions.

首先声明函数,例如:

function doNothing() {
   return false;
}

titles.addEventListener('dragenter', doNothing);
   // Note: this is not invocation like `doNothing()`, but passing a reference

或者,您可以简单地将函数语句包装到匿名函数中。记住,javascript中的函数实际上没有名称,我们只有包含函数的变量。一个匿名函数是没有名字的,它是通过一个隐式的名称赋值来调用的(比如作为一个参数传递参数,它将具有参数的名字),或者通过进行魔术调用来直接调用

Or, you can simply wrap your function statements into an anonymous function. Remember, functions in javascript don't actually have names, we just have variables that contain functions. An anonymous function is one that has no name at all, and it is invoked either by an implicit name assignment (such as being passed as a parameter--where it will have the parameter's name) or by being directly invoked by doing the magic invocation action of putting parentheses after it.

这样看起来像这样:

titles.addEventListener('dragenter', function () { // anonymous function
    return false;
});

如果你想调用一个匿名函数,你必须让javascript知道你想要对待它像一个值,而不是在当前范围内创建一个命名函数的正常快捷方式(其中 function myfun 被视为 var myfun = function )。这是通过将整个事物包含在一组括号中,如下所示:

If you want to invoke an anonymous function, you do have to let javascript know you want to treat it like a value as opposed to the normal shortcut-method of creating a named function in the current scope (where function myfun is treated like var myfun = function). That is done by wrapping the entire thing in one more set of parentheses, like this:

(function () { // begin a function value containing an anonymous function
    // do something
}()); //invoke it, and close the function value

我希望这有助于您更多地了解javascript,为什么你的代码不起作用,你需要做什么才能使它工作。

I hope this helps you understand more about javascript, why your code was not working, and what you need to do to make it work.

这篇关于在javascript中添加多个事件监听器到元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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