将事件动态绑定到表行和列

iha*_*pyk 1 html javascript jquery

我正在尝试仅在第二列上单击事件并在第三列按钮上单击事件,但事件未触发.

HTML:

<table class="table table-bordered table-hover">
      <tr>
        <td class="webIcon">
        <img src="Img/icon.png"></img>
        </td>
        <td class="tabTitle tabRow">Smith</td> 
        <td class="closeTab">
            <button type="button" class="btn btn-default btn-sm " aria-label="Left Align">
                <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
            </button>
        </td>
      </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

jQuery的:

 $( '.table tr:nth-child(2)').delegate("td","click",function(){
            $('.tabRow').click(function(){
                var id = $(this).parents('tr').attr('id');
                console.log(id);
            });
        });

  $( '.table tr:nth-child(3)').delegate("td","click",function(){
            $('.button').click(function(){
                var id = $(this).parents('tr').attr('id');
                console.log(id);
            });
        });
Run Code Online (Sandbox Code Playgroud)

Dip*_*pak 5

您的代码更复杂.试试这个

$( '.table .tabTitle').on("click",function(){            
    var id = $(this).parents('tr').attr('id');
    console.log(id);            
});

$( '.table .btn').on("click",function(){           
    var id = $(this).parents('tr').attr('id');
    console.log(id);
});
Run Code Online (Sandbox Code Playgroud)

$('.table .tabTitle').on("click", function() {

  var id = $(this).parents('tr').attr('id');
  console.log(id);

});

$('.table .btn').on("click", function() {

  var id = $(this).parents('tr').attr('id');
  console.log(id);

});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table class="table table-bordered table-hover">
  <tr id="ID1">
    <td class="webIcon">
      <img src="Img/icon.png"></img>
    </td>
    <td class="tabTitle tabRow">Smith</td>
    <td class="closeTab">
      <button class="btn btn-default btn-sm " aria-label="Left Align">Button
        <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
      </button>
    </td>
  </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

编辑:

  • 如果可以,请避免使用nth-child(n)选择器,因为这会影响页面的加载性能.