zoukankan      html  css  js  c++  java
  • JavaScript中对事件的三种监听方式

    第一种监听方式,也是最普遍使用的方式,是直接在代码上加载事件,产生效果:

    <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>

    在绑定多个相同的事件的时候,前两种方法会产生覆盖,而第三中方法则会同时执行多个事件。

  • 相关阅读:
    无缝世界场景加载的解决方案研究
    3D物体绘制不见
    dx sdk中关于常用dx api的performace性能参数
    OpenGL/DirectX渲染技巧集
    每天送你一個simle
    [原创] 一种页面数据错误输入提示方法
    [原创] ASP.NET 中如何弹出提示窗口然后导向另外一个页面
    [原创] 部署含有ReportView的控件的ASPX页面时出现错误
    公布一个简单的日志记录方法
    [原创] 如何在没有ASP.NET AjaxEnabled Web Site 向导的情况下加入Ajax支持
  • 原文地址:https://www.cnblogs.com/MaxIE/p/972816.html
Copyright © 2011-2022 走看看