如何选择是否没有元素

时间:2018-08-09 14:18:49

标签: jquery css html-table css-selectors jquery-selectors

我希望如果用户点击{strong>不会具有类型为复选框的输入元素的<td>的{​​{1}} ,它将调用一个函数。

实际上,我正在尝试通过这种方式进行操作:

<tr>

我也尝试添加 $(document).on("click", "#mytable tr:has(td)", function (e) { //Some code } ,但也不起作用。

而且这种方式也行不通:

tr:has(td):not(checkbox)

有没有办法做到这一点?看表怎么样: Table

2 个答案:

答案 0 :(得分:2)

您正在使用正确的选择器:not:has,但顺序不正确。试试这个:

$(document).on("click", "#mytable tr td:not(:has(:checkbox))", function(e) {
  console.log('this cell has no checkbox');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="mytable">
  <tr>
    <td><input type="checkbox" /></td>
    <td>Foo</td>
    <td>Bar</td>
  </tr>
  <tr>
    <td><input type="checkbox" /></td>
    <td>Fizz</td>
    <td>Buzz</td>
  </tr>
</table>

答案 1 :(得分:1)

这是您需要的吗?,请考虑使用此代码,tr内的结构无关紧要,如果某处有一个复选框,它将起作用

$(function(){
  $('td').on('click',function(){
  if( $(this).find('input[type="checkbox"]').length == 0 ){
     console.log('this td does not have a checkbox')
  }
  })
})
table{
width:100%;
}

td{
border:1px solid blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <input type="radio"/>
    </td>
    <td>
      <input type="checkbox"/>
    </td>
    <td>
      <p>
         <span>
            <input type="checkbox"/>
         </span>
      </p>
    </td>
  </tr>
</table>