假设页面中很多元素对同一事件都会采用相同的处理方式,这时在每个元素的标记内都要添加一条事件处理的语句就会有很多代码冗余。下面是一个用JavaScript模仿hover伪类效果的例子:
<p onmouseover="this.style.textDecoration='underline'" onmouseout="this.style.textDecoration='none'">用JavaScript模拟p:hover伪类选择器</p>
<p onmouseover="this.style.textDecoration='underline'" onmouseout="this.style.textDecoration='none'">第一段</p>
<p onmouseover="this.style.textDecoration='underline'" onmouseout="this.style.textDecoration='none'">第二段</p>
<p onmouseover="this.style.textDecoration='underline'" onmouseout="this.style.textDecoration='none'">第三段</p>
从代码中可以看出,如果使用事件处理函数的话,那么每个标记内都要写一段相同的事件处理代码,存在很大的代码冗余。那么怎样把它写成通用事件处理程序呢,形如这样的
window.onload = function(){
var oP = document.getElementByTagName("p"); //找到对象
oP.onmouseover= function(){ //设置事件监听函数
……
}}
和IE中的事件监听程序:
oP.attachEvent("onmouseover",fnover);

解决方案 »

  1.   

    <p class="yourType">第一段 </p>
    <p class="yourType">第二段 </p>
    <p class="yourType">第三段 </p> 
    //////////////////////////////////
    window.onload = function()
    {
        var ps = document.getElementsByTagName("p");
        for (var p in ps) 
        {
            if (!ps[p].className) 
            {
                continue;
            }
            if (ps[p].className == "yourType") 
            {
                ps[p].onmouseover = function()
                {
                    this.style.textDecoration = "underline"
                };
                ps[p].onmouseout = function()
                {
                    this.style.textDecoration = "none"
                };
            }
        }
    };