【问题标题】:How to move appended rows up or down using jQuery如何使用 jQuery 向上或向下移动附加的行
【发布时间】:2017-04-17 04:51:09
【问题描述】:

所以基本上,如果 DOM 中已经存在行,它们向上和向下移动行可以完美地工作,但是使用 jquery 附加行并尝试向上和向下移动它是行不通的。

$(".addmore").on('click',function(){
	count=$('table tr').length;
	var data="<tr><td>"+count+"</td>";
      data+="<td><a class='down' href='#'>Down</a> <a class='up' href='#'>Up</a></td>";
  $('table').append(data);
});


$(".up,.down").click(function () {
  var $element = this;
  var row = $($element).parents("tr:first");
  if($(this).is('.up')){
     row.insertBefore(row.prev());
  }
  else{
      row.insertAfter(row.next());
  }
       
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button type="button" class='addmore'>+ Add Row</button>
						
<table>
  <thead>
    <tr>							    
      <th>ID</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody>
    <tr>
    <td>1</td>
      <td><a class="down" href="#">Down</a> <a class="up" href="#">UP</a></td>
    </tr>
  </tbody>
</table>							  	

请运行上面的示例,因为它会清楚地解释。

在此示例中,您可以看到行 ID 1 完美地上下移动,因为它已经存在于表中,但如果我添加更多行,则移动它们不起作用。

【问题讨论】:

    标签: jquery


    【解决方案1】:

    如果您使用以下内容,它甚至可以与新添加的元素一起使用。

    $("table").on("click",".up,.down", function {});
    

    $(".addmore").on('click',function(){
    	count=$('table tr').length;
    	var data="<tr><td>"+count+"</td>";
          data+="<td><a class='down' href='#'>Down</a> <a class='up' href='#'>Up</a></td>";
      $('table').append(data);
    });
    
    
    $("table").on("click",".up,.down", function () {
      var row = $(this).parents("tr:first");
      if($(this).is('.up')){
        row.insertBefore(row.prev());
      }
      else{
        row.insertAfter(row.next());
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <button type="button" class='addmore'>+ Add Row</button>
    						
    <table>
      <thead>
        <tr>							    
          <th>ID</th>
          <th>Action</th>
        </tr>
      </thead>
      <tbody>
        <tr>
        <td>1</td>
          <td><a class="down" href="#">Down</a> <a class="up" href="#">UP</a></td>
        </tr>
      </tbody>
    </table>

    【讨论】:

    • 哇,简单的东西,我疯狂尝试了这么多东西。感谢它的作品。 :)
    • $(".up,.down").click(function () { 有什么问题
    • 问题是 $(".up,.down") 正在生成 jQuery 对象,然后在加载时为其分配点击值。但是,我们想要选择我们的表格,然后我们将过滤 .up 和 .down 的所有元素,这样我们就可以容纳新元素。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    相关资源
    最近更新 更多