par.rowIndex在此代码中为null

时间:2012-12-27 15:01:58

标签: javascript

我是JavaScript的新手,但我不知道为什么这个程序不起作用 我想点击动态创建的按钮,该按钮位于动态创建的表格的单元格中,以获取按钮所在行的rowindex

提前致谢 - 这是我的代码:

<html>
    <head>
        <script>
            function whichrow(obj) {
                var par = obj.parentNode;
                while(par.nodeName.toLowerCase()! = 'tr') {
                    par = par.parentNode;
                }
                alert(par.rowIndex);
            }
        </script>
    </head>
    <body> 
        <script>
        mybody = document.getElementsByTagName("body")[0];
        mytable = document.createElement("table");
        mytablebody = document.createElement("tbody");
        for(var i = 0; i<5; i++) {
            mycurrent_row = document.createElement("tr"); 
            mycurrent_row.id = "row"+i;

            for(var j = 0; j<4; j++) {
                mycurrentcell = document.createElement("td");  
                currenttext = document.createTextNode("Row" + i + "Column" + j);
                mycurrentcell.appendChild(currenttext);
                mycurrent_row.appendChild(mycurrentcell);
            }   
            mybutoncell = document.createElement("td");
            but = document.createElement("button");
            mybutoncell.appendChild(but);

            mycurrent_row.appendChild(mybutoncell);

            mytablebody.appendChild(mycurrent_row);
            but.onClick = whichrow(this);
        }
        mytable.appendChild(mytablebody);
        mybody.appendChild(mytable);

        mytable.setAttribute("border", "2"); 
        </script>
    </body>
</html>                 

2 个答案:

答案 0 :(得分:1)

好的,这里有几点需要注意。

在javascript事件系统中,系统会根据发生的事情,使用自己的包含不同属性的事件对象来调用回调。

所以,这是错误:

  1. 当您分配给事件处理程序时,当您说but.onclick = whichrow(this)时,您正在设置但是请点击whichrow的结果,这是undefined,因为您无论如何都不会回来。它应该是but.onclick = whichrow;,当用户点击您的按钮时,它会调用whichrow。传递的参数是MouseEvent对象。我提供的link应该是了解您可以使用哪种属性的良好开端。

  2. 我必须检查,因为我经常使用el.addEventListeners,但onclick需要小写,而不是像你已经完成的camelCase。

  3. 在事件回调中,this通常是指被点击的元素,因此您应该使用它。

  4. 没有rowIndex属性。

  5. 现在,尝试找到问题的解决方案。可以通过遍历dom来收集rowIndex。我不确定这会起什么作用,因为你手动创建DOM并且已经知道了rowIndex,但是如果它不知道,这就是我要做的事情

    function whichRow(e) {
      // here this should be the button.
      var curRow = this.parentElement.parentElement,
          rowIndex = 0;
    
      while(curRow) {
        curRow = curRow.previousElementChild; 
        rowIndex++;
      }
    
      return rowIndex;
    }
    

    我正在写这篇文章,但重点是提出主要想法。在上面的代码片段中,我采用了按钮父代的父代,因为这是按钮部分的近似标记:

    <tr>
      <td>
        <button></button>
      </td>
    </tr>
    

    因此,button元素的parentElement的parentElement应该为您提供<tr>。然后我们将向后移动,直到我们没有任何先前的元素,依旧计算。一旦前一个元素为null,返回计数。

答案 1 :(得分:0)

您传递给obj的{​​{1}}是一个按钮,我假设在whichrow()内。因此,TD循环将在其第一次迭代中退出,导致while持有par - 其中没有名为TD的属性