简体   繁体   English

有没有一种方法可以在JavaScript中编写事件处理程序,而无需将其添加到标记中或使用addEvent?

[英]Is there a way to write an event handler in JavaScript without adding it to the tag or using addEvent?

Is there a way to add an event listener to an element only by it's ID in JavaScript without using addEventListener or click="eventHandler()"? 有没有一种方法可以仅通过JavaScript中的ID将事件监听器添加到元素,而无需使用addEventListener或click =“ eventHandler()”? I vaguely remember a way to do it using the id of the element. 我隐约记得一种使用元素ID的方法。

For example, here are two ways to add an event listener for a button that I'm not interested in: 例如,以下两种方法可为我不感兴趣的按钮添加事件侦听器:

<input id="myButton" type="button" onclick="doSomething()" />

Here is another: 这是另一个:

myButton.attatchEvent("click", doSomething());

I'm not interested in the above two methods at this time. 我目前对以上两种方法都不感兴趣。 What I'm looking for is something like: 我正在寻找的是这样的:

function myButton_clickHandler(event) {
   alert("hello world");
}

In the code above the browser knows that the event is for "myButton". 在上面的代码中,浏览器知道该事件与“ myButton”有关。

The reason I'm trying to figure this out is for research. 我试图弄清楚这一点的原因是为了研究。 I remember doing something like this in IE. 我记得在IE中做了类似的事情。


UPDATE 更新


I did some more research and I found out that it may be a Microsoft only type of feature set referred to throughout their documentation by the names of, " implicit event handler ", " signature based handlers " and " AutoEventWireup ". 我进行了更多研究,发现它们可能是Microsoft独有的一种功能集,在其整个文档中均通过“ 隐式事件处理程序 ”,“ 基于签名的处理程序 ”和“ AutoEventWireup ”的名称进行引用。 These examples are for ASP.NET. 这些示例适用于ASP.NET。


First example: 第一个例子:

To create a handler for page events 为页面事件创建处理程序

  1. In the code editor, create a method with the name Page_event. 在代码编辑器中,创建一个名为Page_event的方法。

  2. For example, to create a handler for the page's Load event, create a method named Page_Load. 例如,要为页面的Load事件创建处理程序,请创建一个名为Page_Load的方法。

Note: Page event handlers are not required to take parameters the way that other controls event handlers are. 注意:与其他控件事件处理程序一样,不需要页面事件处理程序采用参数。

ASP.NET pages automatically bind page events to methods that have the name Page_event. ASP.NET页自动将页面事件绑定到名称为Page_event的方法。 This automatic binding is configured by the AutoEventWireup attribute in the @ Page directive, which is set to true by default. 自动绑定由@Page指令中的AutoEventWireup属性配置,默认情况下设置为true。 If you set AutoEventWireup to false, the page does not automatically search for methods that use the Page_event naming convention. 如果将AutoEventWireup设置为false,则页面不会自动搜索使用Page_event命名约定的方法。

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Page.IsPostBack Then
        Response.Write("<br>Page has been posted back.")
    End If 
End Sub

Second example: 第二个例子:

To add an event handler implicitly in Visual Basic 在Visual Basic中隐式添加事件处理程序

  1. In the code editor, create an event-handling method with the appropriate signature. 在代码编辑器中,创建一个具有适当签名的事件处理方法。 The method can be named anything you like. 该方法可以命名为任意名称。

  2. Use the Handles keyword, specifying the control and event to which the method should bind. 使用Handles关键字,指定方法应绑定到的控件和事件。

The following code example shows an event handler for the Click event of a button named SampleButton. 下面的代码示例显示了名为SampleButton的按钮的Click事件的事件处理程序。 The method in the example is named Clicked. 示例中的方法名为Clicked。

Protected Sub SampleButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
        Handles SampleButton.Click
    ' Code goes here. 
End Sub

Source: http://msdn.microsoft.com/en-us/library/6w2tb12s%28v=vs.90%29.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1 来源: http : //msdn.microsoft.com/zh-cn/library/6w2tb12s%28v=vs.90%29.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1

In response to your comment, I've written up the below code. 为了回应您的评论,我编写了以下代码。 For each function with an underscore present, the function finds the DOM element whose ID matches the section of the function name before the underscore, and gives the function to it as an onclick handler. 对于存在下划线的每个函数,该函数都会找到其ID与下划线之前的函数名称部分匹配的DOM元素,并将该函数作为onclick处理程序提供给它。

(function() {
    var e, prop;
    for(prop in window) {
        if(prop.indexOf("_") < 0 || typeof window[prop] !== "function") continue;
        e = document.getElementById(prop.split("_")[0]);
        if(typeof e !== "undefined") {
            e.onclick = window[prop];
        }
    }
})();

Paste the above code in, and you'll be able to do what you described in your question, ie attach an event like this: 将上面的代码粘贴到其中,您就可以按照问题中的描述进行操作,即附加如下事件:

function myButton_clickHandler(event) {
    alert("hello world");
}

Where myButton is the ID of your button. 其中myButton是按钮的ID。 This will only work properly if the ID is unique. 仅当ID为唯一时,这才能正常工作。

To expand on Elliot's code, here's a suggestion: 为了扩展Elliot的代码,这里有一个建议:

(function() {
    var prop, match, elem;
    for(prop in window) {
        if( typeof window[prop] !== "function") continue;
        if( match = prop.match(/^(.*)_([a-z]*)Handler$/)) {
            if( e = document.getElementById(match[1])) {
                if( "on"+match[2] in e) {
                    e["on"+match[2]] = window[prop];
                }
            }
        }
    }
})();

With this code, you can have function myButton_clickHandler as in Elliot's answer, but you can also attach other events, such as myButton_focusHandler for onfocus , or someInput_changeHandler . 使用此代码,您可以像Elliot的答案中那样具有function myButton_clickHandler ,但是还可以附加其他事件,例如onfocus myButton_focusHandlersomeInput_changeHandler More importantly, it won't interfere with any functions you might have that happen to have an underscore in them. 更重要的是,它不会干扰您可能碰巧带有下划线的任何功能。 It will only look for functions with names that contain an underscore and have Handler at the end of the name... and even then only if the event type is supported. 它将查找名称包含下划线且名称末尾带有Handler函数,甚至仅在支持事件类型的情况下。

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

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