使用 jQuery 创建可单击的行并排除子元素

Making clickable rows with jQuery and excluding child elements

本文关键字:排除 元素 jQuery 创建 单击 使用      更新时间:2023-09-26

我有一个表格,其中包含我希望可单击的行,但是我的一列中也有一个按钮,按下该按钮时应该执行替代操作。

.HTML:

<table>
    <tr data-url="link.html">
        <td>Some Text Value <input type="button" value="Submit" onclick="otherFunction()"></td>
    </tr>
    <tr data-url="link2.html">
        <td>Some Text Value <input type="button" value="Submit" onclick="otherFunction()"></td>
    </tr>
    <tr data-url="link3.html">
        <td>Some Text Value <input type="button" value="Submit" onclick="otherFunction()"></td>
    </tr>
</table>

j查询:

$(document).ready(function() {
    $('table tr:not(input)').click(function() {
        var href = $(this).attr("data-url");
        if(href) {
            //console.log('redirect to:' + href);
            window.location = href;
        }
    });
});

目前,当我单击按钮时,尽管jQuery选择器排除了任何输入,但页面仍然是重定向的。我是否错误地使用:not

您可以通过

检查 event.target 属性来检查按钮是否被单击,从而在单击处理程序中检查是否单击了按钮

$(document).ready(function() {
  $('table tr').click(function(e) {
    if ($(e.target).is(':button')) {
      snippet.log('button clicked')
      return;
    }
    snippet.log('row clicked');
    var href = $(this).attr("data-url");
    if (href) {
      //console.log('redirect to:' + href);
      window.location = href;
    }
  });
});
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr data-url="link.html">
    <td>Some Text Value
      <input type="button" value="Submit" onclick="otherFunction()">
    </td>
  </tr>
  <tr data-url="link2.html">
    <td>Some Text Value
      <input type="button" value="Submit" onclick="otherFunction()">
    </td>
  </tr>
  <tr data-url="link3.html">
    <td>Some Text Value
      <input type="button" value="Submit" onclick="otherFunction()">
    </td>
  </tr>
</table>

您必须对

传递给 click 函数的event target进行修改。

这是一个工作示例:

$(document).ready(function(){
  $(".clickablerow").click(function(event) {
    if(event.target.tagName != "INPUT"){
      var href = $(this).attr("data-url");
      if(href) {
        //console.log('redirect to:' + href);
        window.location = href;
      }
    }
  });
});
function otherFunction() {
  alert("other function");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tr class="clickablerow" data-url="link.html">
        <td>Some Text Value <input type="button" value="Submit" onclick="otherFunction()"></td>
    </tr>
    <tr class="clickablerow" data-url="link2.html">
        <td>Some Text Value <input type="button" value="Submit" onclick="otherFunction()"></td>
    </tr>
    <tr class="clickablerow" data-url="link3.html">
        <td>Some Text Value <input type="button" value="Submit" onclick="otherFunction()"></td>
    </tr>
</table>