首页 > 解决方案 > 如何使 javascript 代码与按钮一起使用以重新排序表行?

问题描述

下面的代码执行表中行的定位。

javascript中的以下代码与输入类型=“按钮”完美配合

<input type = "button" value = "move up" class = "move up" />

如何使下面的javascript函数与下面的按钮一起使用?

<button type = "submit" class = "btn btn-light" value = "move up">
   <span class = "glyphicon glyphicon-hand-up"> </ span>
</button>

我在下面使用的Javascript代码

$('#mytable input.move').click(function() {
    var row = $(this).closest('tr');
    if ($(this).hasClass('up'))
        row.prev().before(row);
    else
        row.next().after(row);
});

代码 HTML

<table class="table" id="mytable">
  <tr>
    <td>row 1</td>
    <td>
      <input type="button" value="move up" class="move up" />
      <button type="submit" class="btn btn-light" value="move up">
        <span class="glyphicon glyphicon-hand-up"></span>
      </button>
    </td>
    <td>
      <input type="button" value="move down" class="move down" />
      <button type="submit" class="btn btn-light" value="move down">
        <span class="glyphicon glyphicon-hand-down"></span>
      </button>
    </td>
  </tr>
  <tr>
    <td>row 2</td>
    <td>
      <input type="button" value="move up" class="move up" />
      <button type="submit" class="btn btn-light" value="move up">
        <span class="glyphicon glyphicon-hand-up"></span>
      </button>
    </td>
    <td>
      <input type="button" value="move down" class="move down" />
      <button type="submit" class="btn btn-light" value="move down">
        <span class="glyphicon glyphicon-hand-down"></span>
      </button>
    </td>
  </tr>
</table>

标签: javascriptjqueryhtml

解决方案


要使新标记使用 abutton来执行与 相同的input操作,请将脚本更改为此

$('#mytable button.move').click(function() {
    var row = $(this).closest('tr');
    if ($(this).hasClass('up'))
        row.prev().before(row);
    else
        row.next().after(row);
});

然后添加move upbuttons 类

<button type = "submit" class = "btn btn-light move up" value = "move up">
   <span class = "glyphicon glyphicon-hand-up"> </ span>
</ button>

如果您无法将类添加到button,请使用此脚本并评估buttonvalue属性,以确定是“向上”还是“向下”。

$('#mytable button[value="move up"]').click(function() {
    var row = $(this).closest('tr');
    if ($(this).val().contains('up'))
        row.prev().before(row);
    else
        row.next().after(row);
});

请注意,在上面我使用属性选择器button[value="move up"]来定位button. 当然也可以使用它现有的类之一。


推荐阅读