读书人

动态绑定事件出现有关问题。

发布时间: 2013-12-28 22:19:33 作者: rapoo

求助,动态绑定事件出现问题。。。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html" charset="UTF-8">
<title></title>
<script type="text/javascript">
//去除底部的广告
function clearGG(){
var ps=document.getElementsByTagName("p");
ps[ps.length-1].style.visibility="hidden";
}
//改变单元格的背景色
function setBgColor(tddom) {

tddom.style.backgroundColor="red";
}
//去除背景色
function clearBgColor(tddom) {
tddom.style.backgroundColor = "";
}
//为所有的td绑定事件
function binding() {
var inputs = document.getElementsByTagName("input");

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

if (inputs[i].getAttribute("type") == "text") {
//获得文本框的父节点td
var tdp = inputs[i].parentNode;
//为text文本框的得到焦点事件绑定方法
inputs[i].onfocus = function () { setBgColor(tdp); };
//为text文本框的失去焦点事件绑定方法
inputs[i].onblur = function () { clearBgColor(tdp); };
}
}
//去掉广告
clearGG();
}
</script>
</head>
<body onload="binding()">
<form name="form1" action="">
<table border="2" cellpadding="5" cellspacing="5">
<tbody>
<tr>
<td>编号</td>
<td id="t1"><input type="text" name="txtbian" /></td>
<td >名称</td>
<td id="t2"><input type="text" name="txtname" /></td>
</tr>
<tr>
<td>数量</td>
<td><input type="text" name="txtshu" /></td>
<td>金额</td>
<td><input type="text" name="txtjin" /></td>
</tr>
<tr>
<td colspan="2" align="center">总额</td>
<td colspan="2" align="center"><input type="text" name="txtzong" readonly="readonly" /></td>
</tr>
<tr>
<td colspan="4" align="center"><input type="button" id="ntSure" value="确定" /></td>
</tr>
</tbody>


</table>
</form>
</body>
</html>


我这样做是想分别为表格里的text文本框加上焦点事件,实现进入文本时,那个单元格的背景色就为红色。为什么我写的不论焦点在那个文本框变的都是第五个文本框的单元格的背景色。。。是不是方法的参数的问题?求解,要是,要怎么做才能实现我想要的效果呢?
[解决办法]
引用:
Quote: 引用:


//获得文本框的父节点td
// var tdp = inputs[i].parentNode;
//为text文本框的得到焦点事件绑定方法
inputs[i].onfocus = function (e) { setBgColor(e.target); };
//为text文本框的失去焦点事件绑定方法
inputs[i].onblur = function (e) { clearBgColor(e.target); };

我试下,晕,我不知怎么回复你,这样不知道你能不能看到。。

//为text文本框的得到焦点事件绑定方法
inputs[i].onfocus = function () { setBgColor(this); };
//为text文本框的失去焦点事件绑定方法
inputs[i].onblur = function () { clearBgColor(this); };

上面的在chrome下好的
[解决办法]
function binding() {
var inputs = document.getElementsByTagName("input");

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

if (inputs[i].getAttribute("type") == "text") {
//获得文本框的父节点td
//var tdp = inputs[i].parentNode;
//为text文本框的得到焦点事件绑定方法
inputs[i].onfocus = function () { setBgColor(this.parentNode); };
//为text文本框的失去焦点事件绑定方法
inputs[i].onblur = function () { clearBgColor(this.parentNode); };
}
}
你那样的话最后都是去获取最后的 tdp = inputs[i].parentNode;

读书人网 >JavaScript

热点推荐