测试代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
function init() {
var d = document.getElementById( "test" );
d.appendChild(createUl());
console.profile( "f1" );
f1();
console.profileEnd( "f1" );
console.profile( "f2" );
f2(d);
console.profileEnd( "f2" );
}
//普通方式注册事件
function f1() {
var ul = document.getElementById( "testUl" );
for ( var i = 0; i < ul.childNodes.length; i++) {
ul.childNodes[i].onclick = click;
}
}
//事件委托
function f2(d) {
d.onclick = function (e) {
var e = e || window.event;
var target = e.srcElement || e.target;
if (target.tagName == "LI" ) {
alert(target.innerHTML);
}
}
}
function click() {
alert( "1" );
}
function createUl() {
var ul = document.createElement( "UL" );
ul.id = "testUl" ;
var lis = "" ;
for ( var i = 0; i < 200; i++) {
lis += "<li>" + i + "</li>" ;
}
ul.innerHTML = lis;
return ul;
}
|
测试结果:使用事件委托方式性能要高的多
<div id="test_id">
<a href="#" id="11">111111</a>
<a href="#" id="22">222222</a>
<a href="#" id="33">333333</a>
<a href="#" id="44">444444</a>
<a href="#" id="55">555555</a>
<a href="#" id="66">666666</a>
<a href="#" id="77">777777</a>
</div>
1、jquery实现:
$("#test_id").delegate("a", "click", function(event){
var event = event || window.event;
$("#test_id").find("a").each(function(){
$(this).removeClass("current");
});
$(event.target).addClass("current");
});
2、js实现:
var obj = document.getElementByIdx_x("test_id");
obj.addEventListener("click", function(event){
var event = event || window.event;
for(var i=0; i<this.childNodes.length; i++){
if(this.childNodes[i].nodeName.toLowerCase() == ‘a‘){
this.childNodes[i].className = ‘‘;
}
}
var curElem = event.target;
if(curElem.nodeName.toLowerCase() == "a"){
curElem.className = "current";
}
});
原文链接:http://www.cnblogs.com/xqhppt/archive/2011/12/07/2279037.html