挂钩到onClick事件而不使用HTML属性 [英] Hook into an onClick event without using the HTML property

查看:97
本文介绍了挂钩到onClick事件而不使用HTML属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让我的JavaScript和HTML代码分开。要做到这一点,我想确保我从不使用以下语法:

I would like to keep my JavaScript and HTML code separate. To do this, I want to make sure that I never use the following syntax:

<input type="text" name="text" onClick="javascript:onClick(this)" />

但我想挂钩onClick事件,例如上面的输入,但不必使用onClick它的HTML内的属性。此外,我希望使用原始JavaScript而不是像jQuery或MooTools这样的框架来保持它的实现不可知(尽管如果你想提供这些插图和原始JavaScript一样好)。

But I want to hook into the onClick event for example the above input but without having to use the onClick property within it's HTML. Furthermore, I would like to keep it implementation agnostic, using raw JavaScript and not the frameworks like jQuery or MooTools (Although, if you wish to provide those as illustrations along with the raw JavaScript that would be good too).

<input type="text" name="text" />


推荐答案

要使用JavaScript,首先必须添加一个id给你想追加一个事件的元素。这是因为它可以让你很容易理解你的代码,并避免在编写代码时出现混淆。因此,HTML行将如下所示:

To work with JavaScript, first, you have to add an id to the element that you want to append an event. That is because it makes it easy to understand your code and avoids confusion when you are writing your code. So, the HTML line will look like:

<input type="text" name="text" id="myInputType1" />

在整个文档中,每个元素的唯一ID不能多于一个。现在,有三种主要的添加事件的方式:

There must be no more than one id per element that is unique in the whole document. Now, there are three main ways to add events:

/* First */
document.getElementById("myInputType1").onclick = function(){
    /*Your code goes here */
};

/* Second */
function Func(){
    /*Your code goes here */
}
document.getElementById("myInputType1").onclick = Func;

/* Third */
function Func(){
    /*Your code goes here */
}
document.getElementById("myInputType1").addEventListener("click", Func, false);

最后一个优点是您可以添加尽可能多的点击(或鼠标悬停 ,...)事件,并且逐个删除它们也是可能的。但它不适用于IE< 9。相反,您必须使用:

The advantage of the last one is that you can append as many "click" (or "mouseover", ...) events as you like, and removing them one by one is possible too. But it does not work with IE<9. Instead, you have to use:

document.getElementById("myInputType1").attachEvent("onclick", Func);

jQuery方式:

jQuery way:

$("#myInputType1").click(function(){
    /*Your code goes here */
});

这篇关于挂钩到onClick事件而不使用HTML属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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