[英]How to bind event to element?
How to bind event to element in pure javascript: 如何将事件绑定到纯JavaScript中的元素:
This is what JQuery does, how do you accomplish it with pure javascript? 这就是JQuery的功能,您如何使用纯JavaScript来完成它?
$('#arrow_left')
.bind('click', {'c_index': c_index - item_limit },
function(e)
{
var r = e.data.c_index;
}
You would use element.AddEventListener 您将使用element.AddEventListener
target.addEventListener(type, listener[, useCapture]);
And in IE's case (prior to IE9) you would use attachEvent . 在IE的情况下(在IE9之前),您将使用attachEvent 。
bSuccess = object.attachEvent(the_event, function_handler)
//the_event always starts with "on"
Like this: 像这样:
<input id="btn" type="button" value="click me" />
JS: JS:
function click_handler()
{
alert("clicked");
}
var el = document.getElementById("btn");
if(el.addEventListener)//check if this exists
{
el.addEventListener("click", click_handler);
} else {
//then we're on IE older than 9
el.attachEvent("onclick",click_handler);
}
See the demo: http://jsfiddle.net/E8nYr/2/ 观看演示: http : //jsfiddle.net/E8nYr/2/
elem.addEventListener(eventType,
handler,
useCapture);
for IE6,7,8 : 对于IE6,7,8:
elem.attachEvent (event,
handler);
That's the old fashioned way, but you are using jQuery anyways so why changing ? 那是老式的方式,但是无论如何您都在使用jQuery,那么为什么要更改呢?
For non-IE You give it three arguments: the event type, the function to be executed and a boolean (true or false) indicating whether the event handler should be executed in the capturing or in the bubbling phase. 对于非IE,您可以给它三个参数:事件类型,要执行的函数和一个布尔值(true或false),指示是在捕获阶段还是在冒泡阶段执行事件处理程序。 If you're not certain whether you want capturing or bubbling, use false.
如果不确定要捕获还是冒泡,请使用false。
element.addEventListener('click',doSomething,false)
//In IE
element.attachEvent('onclick',doSomething)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.