0

我有一张桌子,每一行都有一个按钮,可以在上面添加一个新行。每行都有新的输入。

我知道如何在表格顶部添加一行,但不是在我单击按钮的每一行顶部。有人可以提供有关如何解决它的提示吗?我也许能做到,但是我看到的解决方案非常复杂,我相信一定有更聪明的解决方案。

哦,我也不知道如何更新函数中发送的参数insertNewRow(id)。到目前为止,这就是我所拥有的:

<script type="text/javascript">
  function insertNewRow(id){
    var row = document.getElementById("bottomRow");
    var newrow = row.cloneNode(true);
    console.log(newrow);
    var newInputs = newrow.getElementsByTagName('input');

    var allRows = row.parentNode.getElementsByTagName('tr');

    row.parentNode.insertBefore(newrow, row);

    var i=row.rowIndex;
    console.log(i);

}
</script>


<table id="myTable">
    <tr>
        <td>Title1:</td>
        <td></td>
        <td>Title2:</td>
        <td></td>
        <td>Title3:</td>    
        <td></td>
        <td></td>
    </tr>

    <tr>

        <td><input class="c1" readonly maxlength="9" size="7" id="gTop" type="text" value ="11"></td>
        <td> <-></td>
        <td id="l1"><input class="c2"  style="width:35px;" maxlength="9" size="7" type="text" id="lTop" value="33"></td>
        <td>=</td>
        <td id="rv1"><input id="rvTop" input class="c2"  style="width:105px;" maxlength="100" size="37" type="text" value="blahblahblah"></td>
        <td></td>
        <td>x</td>  
    </tr>
    <tr id="bottomRow">                 
        <td><input class="c1" readonly maxlength="9" size="7" id="gBottom" type="text" value =""></td>
        <td> </td>
        <td id="l1"><input class="c2"  style="width:35px;" maxlength="9" size="7" type="text" id="lBottom" value="11"></td>
        <td>=</td>
        <td id="rv1"><input id="rvBottom" input class="c2"  style="width:105px;" maxlength="100" size="37" type="text" value="blahblahblah"></td>
        <td><button type="button" onclick="insertNewRow(1)">+</button></td>
        <td>x</td>                      
    </tr>

</table>
4

1 回答 1

2

onclick属性中,不仅仅是调用insertNewRow(),而是执行类似的操作

insertNewRow.apply(this);

属性内的this关键字onclick是点击元素的引用。使用insertNewRow.apply(this),我们将调用insertNewRow()并同时将该this函数调用中的关键字分配给单击的元素,或者在本例中为按钮(如果我们不这样做,this内部insertNewRow()将是对该Window对象的引用) . 然后在你的insertNewRow()函数中,检查当前被点击的元素是否是一个tr元素。如果不是,就上一层,看看那个元素是不是tr元素。继续这样做,直到你到达第一个tr元素。所以,基本上你会寻找最接近的tr元素。

<button type="button" onclick="insertNewRow.apply(this);">+</button>
function insertNewRow(){
    var row = null,
        el = this;
    // Get the closest tr element
    while (row === null)
    {
        if (el.tagName.toLowerCase() === 'tr')
        {
            row = el; // row is now the closest tr element
            break;
        }
        el = el.parentNode;                 
    }

    // Rest of the code here

}​

提琴手

如果您仍然不确定是什么,请查看此处Function.apply()的文档。

于 2012-10-04T14:06:10.103 回答