JavaScript中對事件的三種監聽方式

來源:互聯網
上載者:User

第一種監聽方式,也是最普遍使用的方式,是直接在代碼上載入事件,產生效果:

<table>
<tr onmouseover='this.style.backgroundColor="red"' onmouseout='this.style.backgroundColor=""'><td>text1</td><td>text2</td></tr>
<tr onmouseover='this.style.backgroundColor="red"' onmouseout='this.style.backgroundColor=""'><td>text3</td><td>text4</td></tr>
<tr onmouseover='this.style.backgroundColor="red"' onmouseout='this.style.backgroundColor=""'><td>text5</td><td>text5</td></tr>
</table>

第二種監聽方式,是使用DOM的方式擷取對象,並載入事件:

<table>
<tr><td>text1</td><td>text2</td></tr>
<tr><td>text3</td><td>text4</td></tr>
<tr><td>text5</td><td>text5</td></tr>
</table>
<script>
doms = document.getElementsByTagName('tr');
for(i=0;i<doms.length;i++)
{
    doms[i].onmouseover = function()
    {
        this.style.backgroundColor = "red";
    }
    doms[i].onmouseout = function()
    {
        this.style.backgroundColor = "";
    }
}
</script>

第三種監聽方式,是使用標準的addEventListener方式和IE私人的attachEvent方式,因為IE的attachEvent方式在參數傳遞時的缺陷,這個問題被搞得稍許有些複雜了:

<table>
<tr><td>text1</td><td>text2</td></tr>
<tr><td>text3</td><td>text4</td></tr>
<tr><td>text5</td><td>text5</td></tr>
</table>
<script>
doms = document.getElementsByTagName('tr');
 
function show_color(where)
{
    this.tagName ? where = this : null
    where.style.backgroundColor = "red";
}
 
function hide_color(where)
{
    this.tagName ? where = this : null
    where.style.backgroundColor = "";
}
 
function for_ie(where,how)
{
    return function()
    {
        how(where);
    }   
}
 
for(i=0;i<doms.length;i++)
{
    try
    {
        doms[i].addEventListener('mouseover',show_color,false);
        doms[i].addEventListener('mouseout',hide_color,false);
    }
    catch(e)
    {
        doms[i].attachEvent('onmouseover',for_ie(doms[i],show_color));
        doms[i].attachEvent('onmouseout',for_ie(doms[i],hide_color));
    }
}
</script>

在綁定多個相同的事件的時候,前兩種方法會產生覆蓋,而第三中方法則會同時執行多個事件。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.