JavaScript 动态判断表格 ?
来源:百度知道 编辑:UC知道 时间:2024/05/28 12:54:33
<tr>
<td>第一个表格 </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> <input id="Button1" type="button" value="button" onclick="GetTable(this)" /> </td>
</tr>
</table>
<table>
<tr>
<td>第二个表格 </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> <input id="Button1" type="button" value="button" onclick="GetTable(this)" /> </td>
</tr>
</table>
<table>
<tr>
<td>第三个表格 </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> <input id="Button1" type="button" value="button" onclick="GetTabl
首先同一个Id是只能用一次的,否则会出错
然后加上一个index函数,用来查找当table==table.parentNode.childNodes[i]为true时,i的值
function index(table){
for(var i=0;i<table.parentNode.childNodes.length;i++){
if(table.parentNode.childNodes[i]===table){
return i;
}
}
return false;
}
第一个方法是把第一个button的id改成button2,第二个是button2,第三个是button3,这样的话GetTable就应该把button去掉来取得表格
function GetTable(elem){
return Number(elem.id.replace(/button/,''))--;
}
第二个方法就是不断取得elem的父元素,直到父元素的nodeName是TABLE为止
function GetTable(elem){
var table=elem;
while(table.nodeName!='TABLE' && table.parentNode){
table=table.parentNode;
}
return index(table);
}
function GetTable(obj) {
var tableList=document.getElementsByTagName("table");
var table=null;
while(obj.parentNode){
table=obj.parentNode;
if(table.nodeType==1
&&table.tagName.toLowerCase()=="tabl