删除表中每个动态创建的行的按钮,而不使用onclick

时间:2012-02-27 18:42:54

标签: jquery html

我有多个函数对象从同一个函数声明,用动态添加的行处理它们自己的表。我需要为每一行都有一个删除按钮。由于这些对象可以有多个,因此该行必须知道它所属的对象是什么,并且该对象可以嵌套在其他对象内的某个任意范围内(我认为某些任意函数声明无法实现?), onClick引用其他一些javascript函数的典型解决方案似乎不够。我有一个使用委托来捕获点击的设置,但我不知道从那里去哪里。这是一些示例代码:

function testobject() {
 //other stuff

 $stateadd.click(function() {
  if ($stateselect.val() in states) { //already in array

  } else {
   $temp = $("<tr><td nowrap>" + USStates[$stateselect.val()].Name + "</td><td><input type=\"button\" class=\"testthing\" value=\"Remove\" /></td>").appendTo($selectedstates);
   $temp2 = $temp.find('.testthing');

   $temp.delegate($temp2, 'click', function(e) {
    //how to know what row to delete?  how to know which object the row is in?
    alert($(e.target).attr('class')); //returns proper class, so I can get the button object itself
   });

   states[$stateselect.val()] = $temp;
  }
 });

 //other stuff
}

更清楚一点,我在click事件中需要两件事:构成行的testobject实例和与该行关联的$ stateselect.val()id。我不能只删除行tr / td标签,我还需要从状态对象中删除它。

2 个答案:

答案 0 :(得分:3)

使用this引用单击的元素,然后使用jQuery tr方法找到相应的父closest()元素。

delegate的第一个参数是委托事件应该在其上工作的选择器。你传递了一个jQuery对象,所以它不起作用。试试这个。

$('tableSelector').delegate('.testthing', 'click', function(e) {
    //Here "this" will point to the remove button.

    var $tr = $(this).closest('tr');//this will give you the corresponding row  
});

jQuery closest()获取与选择器匹配的第一个元素,从当前元素开始并逐步向上遍历DOM树。

如果您使用的是最新的jQuery ver(1.7+),则可以使用on方法。

$('tableSelector').on('click', '.testthing', function(e) {
    //Here "this" will point to the remove button.

    var $tr = $(this).closest('tr');//this will give you the corresponding row  
});

注意:您应该将此代码保留在testobject方法之外,因为每次调用delegate方法时都不需要添加ontestobject

更新:根据评论

使用stateselect值将数据属性添加到输入删除按钮。

$temp = $('<tr><td nowrap>' + USStates[$stateselect.val()].Name + '</td><td><input type="button" data-stateid="' + $stateselect.val() + '" class="testthing" value="Remove" /></td>').appendTo($selectedstates);

Js改变

$('tableSelector').delegate('.testthing', 'click', function(e) {
    //Here "this" will point to the remove button.

    var sateId = $(this).data('sateid');
    var $tr = $(this).closest('tr');//this will give you the corresponding row  

    //Here you can access states[stateId] and do what you want
});

答案 1 :(得分:0)

  

“如何知道删除哪一行?”

您可以找到最近的<tr>

$(this).closest('tr')类似,这将是要删除的行。

只需添加到该行的末尾

slideUp('slow', function() { 
    // now that you have slided Up, let's remove it from the DOM
    $(this).remove(); 
});

所以,您只需删除点击部分并添加:

$(document).on('click', '.testthing', function(e) {
    alert($(e.target).attr('class'));

    var tr = $(this).closest('tr');
    tr.slideUp('slow', function() { 
        // now that you have slided Up, let's remove it from the DOM
        $(this).remove(); 
    });
});