我想在点击按钮后触发btnClick()方法,然后在表格中添加10行,并且每行都绑定一个事件,点击行时弹出该行是第几次添加.就是i的值 function btnClick(){
//获得tbody对象
var t_body=document.getElementById("t_body");
var str="";
for(var i=0;i<10;i++){
//插入行
str=i;
var t_tr=t_body.insertRow(i);
//插入列
t_tr.insertCell(0).innerText=0;
//给列绑定onclick事件
t_tr.onclick=function(){
alert(str);
}
}
} <input type="button" value="click" onClick="btnClick()"/>
<table border="1" >
<tbody id="t_body">
</tbody>
</table>
这样写行可以添加但是点击那一行都是弹出9.
//获得tbody对象
var t_body=document.getElementById("t_body");
var str="";
for(var i=0;i<10;i++){
//插入行
str=i;
var t_tr=t_body.insertRow(i);
//插入列
t_tr.insertCell(0).innerText=0;
//给列绑定onclick事件
t_tr.onclick=function(){
alert(str);
}
}
} <input type="button" value="click" onClick="btnClick()"/>
<table border="1" >
<tbody id="t_body">
</tbody>
</table>
这样写行可以添加但是点击那一行都是弹出9.
alert(str);
}
这里面你为什么要alert出来str呢?alert出来一个i不就可以了么?当然了,如果你直接写成
t_tr.onclick=function(){
alert(i);
}这样也许每一次都是undefined。
因此你可以吧这里的代码改成这样:t_tr.onclick=function(i){
return function(){
alert(i);
};
}这样可以解决你的问题。
<head>
<script type="text/javascript" src="../Scripts/jquery-1.3.2.js"></script>
<script type="text/javascript">
$().ready(function () {
$("#button").click(function () {
for (var i = 0; i < 10; i++) {
$("#table").append("<tr id=" + i + "><td>0</td></tr>");
}
$("table tr").click(function () {
alert(this.id);
});
});
});
</script>
</head>
<body>
<input type="button" value="click" id="button" />
<table border="1" id="table"></table>
</body>
</html>
<html>
<head>
<script type="text/javascript">
function doSomething() {
var table = document.getElementById("table");
for (var i = 0; i < 10; i++) {
var R = table.insertRow();
var C = R.insertCell();
C.id = i;
C.onclick = function trclick() {
alert(this.id);
}
C.innerHTML = "0";
}
alert(table.innerHTML);
}
function trclick(v) {
alert(v);
}
</script>
</head>
<body>
<input type="button" value="click" id="button" onclick="doSomething()" />
<table border="1" id="table">
</table>
</body>
</html>