当用户使用 jquery 的点击事件点击表格时,如何选择表格的行

How to select row of a table when user taps on it using tap event of jquery?

本文关键字:表格 何选择 选择 用户 事件 jquery      更新时间:2023-09-26

>我有一个表格

<table>
    <tr> Row 1 </tr>
    <tr> Row 2 </tr>
    <tr> Row 3 </tr>
</table>

现在我需要编写一个代码,以便当我通过点击平板电脑选择一行或多行时,应该启用继续按钮,否则应该禁用它。我是jQuery的新手,所以无法将其放入代码中。

假设您的表有 id 表,并且应该启用的按钮具有 id 按钮:

  $( "#table tr" ).bind( "tap", tapHandler );
    function tapHandler( event ){
          $( event.target ).toggleClass( "tapped" );
         if($(".tapped").size() > 0)
           $("#button").attr("disabled", false);
       else $("#button").attr("disabled", true);

      }

示例 html 标记(您必须在 tr 中嵌套td元素,不能直接在tr下插入文本):

<table>
    <tr>
        <td><input type="button" value="Foo" class="btn" disabled="disabled" /></td>
    </tr>
</table>

j查询:

$(function(){
    $('table tr').bind('touchend', function(){
        $(this).toggleClass('selected');
        if ($(this).hasClass('selected'))
            $(this).find('.btn').removeAttr('disabled');
        else
            $(this).find('.btn').attr('disabled', 'disabled');
    });
});

在此处查看 jsFiddle 示例:http://jsfiddle.net/up5wf2o4/

  • 注意:我使用了touchend事件,因为您可能不支持tap事件,除非您使用的是jQuery Mobile或任何其他支持库。 如果是这样,请继续并将touchend替换为 tap

希望有帮助。

这是您的表格,其中包含一些修改(我添加了TD元素):

<table> 
    <tr data-row="row 1"><td> Row 1 </td></tr> 
    <tr data-row="row 2"><td> Row 2 </td></tr> 
    <tr data-row="row 3"><td> Row 3 </td></tr> 
</table>

事件处理:

  $( "table tr" ).bind( "tap", tapHandler );
  function tapHandler( event ){
      var dataRow = $( this ).attr("data-row");
      alert( dataRow);
  }

小提琴