JavaScript事件注册而不使用jQuery [英] JavaScript event registering without using jQuery
问题描述
如何在不使用jQuery的情况下正确执行以下操作。
How to correctly do something like the following without using jQuery.
$(document).ready(function(){
$("#someButton").click(function(){
alert("Hello");
});
});
谢谢。
推荐答案
最简单的方法是:
// DOM Level 0 way
window.onload = function () {
document.getElementById("someButton").onclick = function() {
alert("Hello");
};
};
这适用于所有浏览器,但请注意,使用此方法只能一个事件处理程序可以附加到事件。
This will work on all browsers but note that with this approach only one event handler can be attached to an event.
还要注意 onload
事件并不完全等同于jQuery的事件 ready
事件, onload
将在页面的所有资源被完全加载时被触发(图像,子帧,等等...),而 ready
在解析DOM后立即触发。
Also notice that the onload
event is not completely equivalent to the jQuery's ready
event, onload
will be fired when all the resources of the page are completely loaded (images, sub-frames, etc...), while ready
fires as soon the DOM has been parsed.
如果你想附加多个事件处理程序,您可以使用 DOM Level 2 标准 element.addEventListerner
方法(或 element.attachEvent
If you want to attach multiple event handlers, you can use the DOM Level 2 Standard element.addEventListerner
method (or element.attachEvent
for IE)
获得交叉的最简单的抽象-browser绑定事件的方法是:
The simplest abstraction to get a cross-browser way to bind events is:
function addEvent(el, eventType, handler) {
if (el.addEventListener) { // DOM Level 2 browsers
el.addEventListener(eventType, handler, false);
} else if (el.attachEvent) { // IE <= 8
el.attachEvent('on' + eventType, handler);
} else { // ancient browsers
el['on' + eventType] = handler;
}
}
然后你可以:
var button = document.getElementById("someButton");
addEvent(button, 'click', function () {
alert("Hello");
});
addEvent(button, 'click', function () {
alert("world!");
});
还要注意 addEventListener
和IE的 attachEvent
方法有其不同之处,当您使用 addEventListener
将多个处理程序附加到事件时,它们将被触发顺序,当处理程序被绑定(FIFO)时, attachEvent
将以相反的顺序(LIFO)触发处理程序。
Be aware also that the addEventListener
and the IE's attachEvent
methods have their differences, when you attach multiple handlers to an event with addEventListener
they will be fired in the same order, as the handlers were bound (FIFO), attachEvent
will trigger the handlers in the contrary order (LIFO).
查看示例此处。
这篇关于JavaScript事件注册而不使用jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!