且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Jquery编辑和删除新添加的表行

更新时间:2023-12-05 20:35:52

您可以利用DOM遍历和.live()来完成这项工作.使用.live()将侦听器添加到表的行中.在此方法内部,确定单击了哪个元素(e.currentTarget).您可以使用简单的条件来检查它是否是需要响应的按钮.然后,使用DOM遍历确定您想要发生的事情.例如,如果e.currentTarget是删除按钮,则可以使用$(this).closest('tr').remove();删除行.如果您需要通过ajax与数据进行交互,请让ajax函数支持传递您需要执行删除操作的所有值(id).为了获取id,您需要从ajax调用中获取它并将其放置在DOM中的某个位置,以便可以在需要时检索它.生成tr时,您始终可以输入'title'属性.

You could take advantage of DOM traversal and .live() to make this work. Add a listener using .live() to the rows of the table. Inside this method, determine which element was clicked (e.currentTarget). You can use a simple conditional to check if it was a button that needs to react. Then, use DOM traversal to nail down what you want to have happen. For example, if e.currentTarget is the delete button, the you can use $(this).closest('tr').remove(); to delete the row. If you need to interact with the data through ajax, make your ajax function support passing in whatever valus you'd need (id) to perform the delete. In order to obtain the id, you'll need to get it from the ajax call and put it somewhere inside the DOM so you can retrieve it when you need it. You can always toss in a 'title' attribute when the tr is generated.