您的位置:首页 > Web前端 > JavaScript

如何使用js减少页面大量重复(js事件)语句

2009-05-08 17:03 666 查看
看了很多人的代码,特别是一些鼠标移进移出变色的代码块,真是一个字,惨啊

<tr onMouseOver="this.bgColor='#ff0000'" onmouseout="this.bgColor='#cccccc'">

<td>内容</td>

</tr>

<tr onMouseOver="this.bgColor='#ff0000'" onmouseout="this.bgColor='#cccccc'">

<td>内容</td>

</tr>

<tr onMouseOver="this.bgColor='#ff0000'" onmouseout="this.bgColor='#cccccc'">

<td>内容</td>

</tr>

.....

现在给你一种更方法更易维护的方法,首先输出html代码如下

<table id="onTab">

<tr>

<td>标韪栏我颜色不变</td>

</tr>

<tr rel="onMouse">

<td>内容栏我颜色想变</td>

</tr>

<tr rel="onMouse">

<td>内容栏我颜色想变</td>

</tr>

<tr rel="onMouse">

<td>内容栏我颜色想变</td>

</tr>

</table>

<script type="text/javascript">trBgColor("onTab");</script>

当显示完后,在使用js 调用 函数如 trBgColor

function trBgColor(obj){

var x = document.getElementById(obj); //只读id为obj值的内容块

var y = x.getElementsByTagName("tr"); //读tr

for (var i=0;i<y.length;i++){

if(y[i].getAttribute("rel") == "onMouse"){

//只有当tr元素 rel为 onMouse才值行以下操作,你也可以去掉这个条件

y[i].onmouseover=xxxover; //移进

y[i].onmouseout=xxxout; //移出

y[i].ondblclick=xxxdbl; //还可以加个双击事件,你也可以加onclick等等各事件

}

}

}

function xxxover(){

this.style.background="#ffc";

}

function xxxout(){

this.style.background="#fff";

}

function xxxdbl(){

alert("你双击我了");

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐