【问题标题】:How to select if has not an element如果没有元素如何选择
【发布时间】:2019-01-17 01:28:11
【问题描述】:

我希望,如果用户单击<tr> 中的<td> 并且 具有checkbox 类型的输入元素,它将调用一个函数。

其实我是在尝试这样做的:

 $(document).on("click", "#mytable tr:has(td)", function (e) {
     //Some code
 }

我也尝试添加tr:has(td):not(checkbox),但也不起作用。

而且这种方式也没有用:

if (e.toElement === "input"){
    return;
}

有没有办法做到这一点?看看桌子怎么样:

【问题讨论】:

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


    【解决方案1】:

    您使用了正确的选择器,: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>

    【讨论】:

      【解决方案2】:

      这是你需要的吗?考虑一下这段代码,不管你在 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>

      【讨论】:

        猜你喜欢
        • 2015-03-13
        • 2022-01-19
        • 2011-02-07
        • 1970-01-01
        • 2019-06-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多