js删除元素 尚学堂drp中的问题

今天在学尚学堂drp的时候发现其中有点问题。但是找了半天就是不知道,最后一分析,原来是id重复的问题。主要是那老师的代码也是有问题的,但是问题偶尔出现。

其核心的js代码如下:


 var rowIndex = 0;

function addOneLineOnClick() {
  var row=tblFlowCardDetail.insertRow(tblFlowCardDetail.rows.length);
  var col = row.insertCell(0);
  col.innerHTML = "<input readonly=\"true\" maxLength=6 size=6 name=aimId><input type=button  value =...   name=btnSelectAimClient index=\""+ rowIndex +"\" onclick=\"selectAimClient(this.index)\">";
  col = row.insertCell(1);
  col.innerHTML = "<input id=aimName name=aimName size=25 maxlength=25 readonly=\"true\">";
  col = row.insertCell(2);
  col.innerHTML = "<input readonly=\"true\" maxLength=6 size=6 name=itemNo><input type=button  value =...   name=btnSelectItem index=\""+ rowIndex +"\" onclick=\"selectItem(this.index)\">";
  col = row.insertCell(3);
  col.innerHTML = "<input id=itemName name=itemName size=25 maxlength=25 readonly=\"true\">";  
  col = row.insertCell(4);
  col.innerHTML = "<input id=spec name=spec size=10 maxlength=10 readonly=\"true\">";
  col = row.insertCell(5);
  col.innerHTML = "<input id=pattern name=pattern size=10 maxlength=10 readonly=\"true\">";
  col = row.insertCell(6);
  col.innerHTML = "<input id=unit name=unit size=4 maxlength=4 readonly=\"true\">";
  col = row.insertCell(7);
  col.innerHTML = "<input id=qty name=qty size=6 maxlength=6>";
  col = row.insertCell(8);
  col.innerHTML = "<input type='button' value='删除' id=btnDeleteLine name=btnDeleteLine onclick=\"return DeleteRow('row" + rowIndex + "')\"></tr>";
  row.setAttribute("id", "row" + rowIndex);
  rowIndex++;
 }
 
 function DeleteRow(rowTag){
      var i = tblFlowCardDetail.rows(rowTag).rowIndex;
   var j;
  for(j=i;j<=rowIndex;j++) { 
   tblFlowCardDetail.rows(j).cells(0).all("btnSelectAimClient").index--;
   tblFlowCardDetail.rows(j).cells(2).all("btnSelectItem").index--; 
  }
        tblFlowCardDetail.deleteRow(i);
  rowIndex--;
 }


问题就出在:

  row.setAttribute("id", "row" + rowIndex); 和rowIndex--;上面

当删除一行的时候,rowIndex--,而id没有变,

加入添加了两行,两行的id分别是row0和row1,这时rowIdex也变成了2,这时把row0删除了,所以rowIndex减一,变成了1,这个时候再加一行,新加的这行的id也成了row1(因为这时rowIndex等于1),所以这时候就存在两行的id都为row1的情况,所以删除的时候,就会出错,我试过了,如果找不到的话,他会从第一行开始删除。

其实我觉得那天我的那个办法还行,就是rowIndex不减,直接加到id里面,但是这样rowIndex会变的很大,如果长时间操作的话,但是个人认为这对性能影响不大,其实进行减的时候,同样耗时。

你可能感兴趣的:(J#)