【问题标题】:add type to DOM element with JQuery [duplicate]使用 JQuery 向 DOM 元素添加类型 [重复]
【发布时间】:2014-09-14 10:02:30
【问题描述】:

我试图将type=checkbox 附加到每个tr 的最后一个td

我一直在想通过遍历来实现这一点,但我不知道它是否可行。类似的东西。

$('#myID tr').children("td:nth-last-of-type(1)").addClass("me");

我知道这是向元素添加一个类,但是可以以类似的方式将TYPE 添加到tr DOM 元素吗? 有一两个例子,比如this 一个,但都是在改变类型而不是添加新的。

<table id="myID" class="myClass">
    <tr>
        <th>one</th>
        <th>two</th>
        <th>three</th>
        <th>four</th>
    </tr>
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
    </tr>
    <tr>
        <td>a</td>
        <td>b</td>
        <td>c</td>
        <td type='checkbox'></td>    <!--  **THIS IS WAHT IM AFTER**  -->
    </tr> 
</table>

<input type='button' id='but_id' value='Click Me'/>

【问题讨论】:

  • 它是设置,没有改变,它应该可以工作......你试过了吗? (谈论链接中的示例)
  • 使用.attr("type",'checkbox') 而不是.addClass("me")
  • 我认为&lt;td&gt; 元素不应该包含type="checkbox"?
  • @RajaprabhuAravindasamy - 很简单,嘿。非常感谢。
  • &lt;td&gt; 根本没有 type 属性。见:developer.mozilla.org/en-US/docs/Web/HTML/Element/td

标签: javascript jquery html


【解决方案1】:

您不能将type="checkbox 添加到 td,它是无用且无效的,但您可以将复选框添加到 td 例如

$('#myID tr').children("td:nth-last-of-type(1)").append('<input type="checkbox" />');

【讨论】:

    【解决方案2】:

    您可以将输入元素附加到 td。

    $(document).ready(function () {
            $('#myID tr').children("td:nth-last-of-type(1)").append("<input type='checkbox'/>");
        });
    

    演示:http://plnkr.co/edit/qVIUDfAxp2vUIxw2AQEp?p=preview

    【讨论】:

      【解决方案3】:

      您不能在 td 中添加type = 'checkbox',它是无效的。只需在 td 中追加输入类型

      $('#myID tr').find("td").last().append("<input type='checkbox' />");
      

      evert last td 意味着

       $('#myID tr').find("td:nth-last-child(1)").append("<input type='checkbox' />");
      

      DEMO

      【讨论】:

        【解决方案4】:

        添加type = 'checkbox' 并不意味着它的html 错误。您可以在 td 中添加复选框。

        $('#myID tr').children("td:last-child").append('<input type="checkbox" />');
        

        DEMO

        【讨论】:

          【解决方案5】:

          您的意思是在最后一个单元格中附加一个复选框吗?试试这个。

          $("#myID tr td:last-child").append("<input type='checkbox' />");
          

          http://jsbin.com/zerocasu/2/edit

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2019-03-10
            • 1970-01-01
            • 2013-06-03
            • 2016-05-11
            • 2011-01-27
            • 1970-01-01
            • 2010-09-28
            • 2012-05-31
            相关资源
            最近更新 更多