《悟透JavaScript》学习札记之响应DOM事件

响应DOM事件的两种方式:

1. 静态绑定(JS代码写在HTML标签的事件属性里面):

<div onclick="alert('This is a ' + this.tagName)">Click Me Static!</div> // output: This is a DIV

2.动态绑定(DOM对象的事件属性与事件处理函数关联):

               <div id="aDiv">Click Me Dynamic!</div>
<script type="text/javascript">
aDiv.onclick = ClickMe;
function ClickMe()
{
alert('This is a ' + this.tagName);
};

    output: This is a DIV

---------------------------------------------------------------------------------------------------------------------------------------------------

onclick = "..."  <=> id.onclick = function(){...};

例子:

<div onclick="ClickMe()">Click Me!</div>

等价于aDiv.onclick = function(){ClickMe()};

此时ClickMe函数内的this参数并非触发事件的DOM对象本身,而是全局的window对象。output: This is a undefined

对象传递可解决上述问题,如<div onclick = "ClickMe.call(this)">Click Me</div> // output: This is a DIV

但是<div onclick="ClickMe(this)">ClickMe(this)!</div> // output: This is a undefined


你可能感兴趣的:(JavaScript,html,function,div,output)