Home > Web Front-end > JS Tutorial > body text

Javascript动态绑定事件的简单实现代码_javascript技巧

WBOY
Release: 2016-05-16 18:13:23
Original
1040 people have browsed it

下面是页面的dom结构

复制代码 代码如下:


  • One

  • Two

  • Three

  • Four



下面是javascript代码
复制代码 代码如下:

//根据ID获取对象
function id(v) { return document.getElementById(v); }

//根据标记获取对象
function tag(element, t) { return element.getElementsByTagName(t); }

window.onload = function() {
//获取test下的所有li对象
var li = tag(id("test"), "li");

//用循环绑定鼠标单击事件
for(var i=0; ili[i].onclick = function() {
//期望弹出1,2,3,4
//结果弹出的总是5
alert("你点击了第" + (i+1) + "项");
}
}
}

为什么会出现上边的现像呢?原因是“for中的事件绑定并没有马上得到执行”。修改后的代码如下:
复制代码 代码如下:

//根据ID获取对象
function id(v) { return document.getElementById(v); }

//根据标记获取对象
function tag(element, t) { return element.getElementsByTagName(t); }

window.onload = function() {
//获取test下的所有li对象
var li = tag(id("test"), "li");

//用循环绑定鼠标单击事件
for(var i=0; i(function() {
var t = i
li[i].onclick = function() {
alert("你点击了第" + t + "项");
}
})();
}
}

测试代码,一切OK,我们正常的将循环变量i传到onclick事件对应的处理函数中。
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!