愈之 博客


A breath of fresh air


事件传播机制---记一道笔试题

今天笔试有这么一道题:

要求是这样的: 要点击DIV2,先提示里面的,再提示外面的, 点击DIV4,先提示外面的,再提示里面的。

1
2
3
4
5
6
<div id="div1" style="border:1px solid #f00;height:200px;width:200px">外面的
<div id="div2" style="border:1px solid #000;height:150px;width:150px">里面的</div>
</div>
<div id="div3" style="border:1px solid #f00;height:200px;width:200px">外面的
<div id="div4" style="border:1px solid #000;height:150px;width:150px">里面的</div>
</div>

我知道这是在考察事件传播模型,我对这个模型理解也很透彻。于是为了从时间角度考虑,我动了一些小聪明就这伪造了一份效果一样的代码,请原谅我原谅我。。。后面补上我认为的正确代码。

1
2
3
4
5
6
7
8
9
10
11
$(function(){
$('#div2).on("click",function(){
alert("里面的");
alert("外面的");
});
$('#div4).on("click",function(){
alert("外面的");
alert("里面的");
});
});

当然还引入了jquery库,最后还不忘卖萌写注释说明我为了节约时间这么写。

回来研究一下event对象,dom属性。写下来这些答案:

1
2
3
4
5
6
7
8
9
10
11
12
13
window.onload = function(){
document.getElementByIdx_x_x("div1").addEventListener("click", ff1,false);//关键在于第三个参数//captureFlag
document.getElementByIdx_x_x("div2").addEventListener("click", ff1,false);
document.getElementByIdx_x_x("div3").addEventListener("click", ff2,true);
document.getElementByIdx_x_x("div4").addEventListener("click", ff2,true);
function ff1(){
alert(this.childNodes[0].nodeValue);
};
function ff2(){
alert(event.currentTarget.childNodes[0].nodeValue);
};
}

这笔试时间真是紧。