如何使javascript代码与按钮配合使用以对表行进行重新排序?

时间:2018-07-05 20:23:08

标签: javascript jquery html

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

下面的javascript代码与输入类型=“ button”完美配合

<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>

2 个答案:

答案 0 :(得分:1)

要使用buttoninput进行新标记,请将脚本更改为此

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

然后将move up添加到button的类中

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

如果无法将类添加到button,请使用此脚本并评估button value 属性,以查找是否要“向上移动” ”或“向下”。

$('#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。当然,也可以使用其现有的类之一。

答案 1 :(得分:-1)

将元素设为input.move而不是button.move,因为元素是按钮而不是input。这是更新的JS。

$('#mytable button.move').click(function() { 
var row = $(this).closest('tr'); 
if ($(this).hasClass('up'))//update call here or add to html 
class row.prev().before(row); 
 else row.next().after(row); 
});

观察上面的评论更新类,像这样添加到按钮类...

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