使用 jQuery 将对象绑定到一行

binding objects to a row with jquery

本文关键字:一行 jQuery 对象 绑定 使用      更新时间:2023-09-26

我有一些表格数据,一个产品列表。

id | name | description | options
1  | foo  | bar         | [delete]

现在通常我只是在删除按钮上设置一个类,例如 .delete-item 并执行

$('.delete-item').click(function(e) {
     e.preventDefault();
     // do something/ajax etc
});

但是有了这个,我将添加一些其他功能,例如描述的内联编辑。现在我可以绑定另一个函数,例如我的删除函数,但我想知道是否有一种更多的 jquery 方法来做到这一点,因为我以后可能会通过自动计算总数来添加产品价格和数量,它可能会变得非常毛茸茸的。

也许是一个插件,或者某种对象?

$('table').productEditor();

这有意义吗?我去读这种事情有什么吗?

你可以写一个小的jQuery插件来做到这一点:

//tableEditor.js
;(function($){
    $.fn.tableEditor = function(settings) {
        var defaults = {stuff: 1, etc: true};
        settings = $.extend(defaults, settings || {});
        //using "on" so we wouldn't have to use multiple handlers for each link
        this.on('click', '.delete-item', function() { 
            e.preventDefault();
            var this_row = $(this).closest('tr');
            // do stuff
        });
        this.on('click', '.edit-item', function() { 
            e.preventDefault();
            var this_row = $(this).closest('tr');
            // do stuff
        });
        return this;
    };
})(jQuery);

然后像这样称呼它:

//main.js
$(function() { 
    $('#table').tableEditor({etc: false}); 
});

你可以做:

编辑 :对于动态添加的行,请使用委托形式的.on()

$("#myTable").on("click", "td", function (event) {
    var thisID = $(this).siblings("td").eq(0).text(); // get ID of clicked row
    switch (event.target.className) {
        case "delete":
            //delete              
            alert("delete this ID = " + thisID);
            break;
        case "edit":
            // edit
            alert("edit this ID = " + thisID);
            break;
        default:
            return false;
    }
}); // on click

您仍然需要为每个可点击的td添加一个

请参阅新的 JSFIDDLE,其中包含一种添加行的方法。

注意.on()需要 jQuery v1.7+