jquery使用.on动态移动行

时间:2013-09-19 00:43:03

标签: javascript jquery html

我正在尝试在两个表之间移动行,但我不能让它将click事件绑定到它。我对.on事件中的选择器部分感到困惑,我不确定我应该以什么为目标。

基本上我可以让它移动到一个表,然后返回然后它会丢失click属性。不知道为什么。

我附上了一个小提琴(http://jsfiddle.net/Yjqkn/216/)来使问题更加清晰。批准按钮将其向下移动,等待列表按钮将其移回,但随后失去所有事件监听器我是否需要使用.bind重新绑定它们。解决此问题的最佳方法是什么。

我试过了:.on("click","button.remove-participant",function()无效

的Javascript

$( ":button" ).on("click",function(){

    if($(this).hasClass('remove-participant')) {
        $(this).removeClass('remove-participant').addClass('add-participant');
        $(this).html('Approve');
        var current_row = $(this).closest('tr').html();

        $('.table_2 > tbody:last').append('<tr>'+current_row+'</tr>');
        $(this).closest('tr').remove();

        $( ".table_2 .add-participant" ).bind( "click", function() {
            $(this).removeClass('add-participant').addClass('remove-participant');
            var current_row = $(this).closest('tr').html();
            $(this).html('Waitlist');

            $('.table_1 > tbody:last').append('<tr>'+current_row+'</tr>');
            $(this).closest('tr').remove();
        });
    }
});

HTML

<table class="table_1">
  <tr>
    <th>Info Header 1</th><th>Info Header 2</th>
  </tr>
  <tbody>
    <tr><td>Don</td>
      <td><button class="remove-participant" name="">Remove</button></td>
    </tr>
  </tbody>
</table>
<table class="table_2">
  <tr>
    <th>Info Header 1</th><th>Info Header 2</th>
  </tr>
  <tbody>
    <tr></tr>
  </tbody>
</table>

2 个答案:

答案 0 :(得分:1)

您应该使用:

$(".table_1").on("click", "button.remove_participant", function() {
    ...
});

事件委托的一般思想是将处理程序绑定到DOM中的一些静态元素,并包含所有动态添加的元素。然后 selector 参数应指定要委派给的更具体的动态元素。

click点击处理程序中将.table_2 .add_participant处理程序绑定到button.remove_participant似乎也不正确。每次删除参与者时,它都会为每个.add_participant元素添加另一个单击处理程序,因此当您单击这些元素时,处理程序将多次运行。您应该只委托一次处理程序 - 整个委托点就是它获取动态更改,因此您不需要在每次修改DOM时重做它。

BTW,

.removeClass('class1').addClass('class2');

可以组合成:

toggleClass('class1 class2');

答案 1 :(得分:-1)

在我看来,你的代码不起作用是因为你的逻辑。您在此处执行此操作:在表1中,您将删除该类。               $(本).removeClass( '删除参与者')addClass( '添加参与者')。

当你点击表2时,做同样的事情。但是你永远不会回过头来在表1中添加remove-participant类。所以表1中的点击不起作用,因为class被设置为'add-participant'而没有改回来。