javascript 在最后一行之前向表格添加一行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22856003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:53:36  来源:igfitidea点击:

Add a row to table before last row

javascriptjqueryhtml

提问by AaA

I have following HTML/Script code

我有以下 HTML/脚本代码

<script type="text/javascript">
    $(function(){
        $(".AddItem").click(function(){
            $(this).parents('table tr:last').after('<tr><td>&nbsp;</td><td><input type="text" name="item[]" value=""></td></tr>');
            return false;
        });
    });
</script>
<table>
    <tr>
        <td valign="top">Items&nbsp;<a href="#" class="AddItem"><img src="images/16/button-add.png"  title="Add more Items"></a></td>
        <td><input type="text" name="item[]"  ></td>
    </tr>
    <tr>
        <td>Count: </td>
        <td>10</td>
    </tr>
</table>

This will add a row below the row with add button. I need to add a row at the bottom of table above footer row (Count). What selector should I use?

这将在带有添加按钮的行下方添加一行。我需要在页脚行(计数)上方的表格底部添加一行。我应该使用什么选择器?

Please note this questiondoes not meet my requirement, It selects the last row.

请注意这个问题不符合我的要求,它选择最后一行。

回答by Tushar Gupta - curioustushar

Try .prev()

试试.prev()

Fiddle Demo

Fiddle Demo

$(this).closest('table').find('tr:last').prev().after('<tr><td>&nbsp;</td><td><input type="text" name="item[]" value=""></td></tr>');

回答by Anoop Joshi

USe .before()for that

使用.before()

 $(this).parents('table tr:last').before('<tr><td>&nbsp;</td><td><input type="text" name="item[]" value=""></td></tr>');

Edit

编辑

$(this).parents('table').find("tr:last").before('<tr><td>&nbsp;</td><td><input type="text" name="item[]" value=""></td></tr>');

回答by AMS

$(function(){
        $(".AddItem").click(function(e){
            $("tr:last", $(this).parents('table')).before('<tr><td>&nbsp;</td><td><input type="text" name="item[]" value="+"/></td></tr>');
            return false;
        });
    });

you can also try this

你也可以试试这个