如何使用jquery删除td标签中的内容

How to remove the content in the td tag using jquery

本文关键字:标签 td 何使用 jquery 删除      更新时间:2023-09-26

我有一个表定义为

<table>
  <tr>
    <td>
       <input type='text' />
    </td>
    <td>
      <button id ='first'>Button</button>
    </td>
    <td>
      <input type='text' />
   </td>
 </tr>

$("#first").live('click',function(){
    $(this).prev().remove();
    $(this).remove();
});

如何删除前一个元素的td。但是我不想删除td

如果您想要删除前一个TD的完整内容(而不是特定的INPUT元素),则可以这样做:

$(document).on("click", "#first", function() {
    $(this).closest("td").prev().empty();
});

http://jsfiddle.net/sfHBn/1/

$(document).on("click", "#first", function() {
    $(this).closest("td").prev().html("");
});

这将删除之前的td标签中的所有内容。

您应该向上到DOM树直到父<td>,然后获得之前的<td>,找到<input>并将其删除。您应该使用带有事件委托的on(),而不是已弃用的live():

$(document).on("click", "#first", function() {
    $(this).closest("td").prev().find("input").remove();
});

注意,您可以使用#first的其他静态父元素来代替document

我建议你使用.on()代替,因为.live()现在从jQuery 1.9+版本中删除了:

$(document).on('click', "#first", function(){
   $(this).closest('td').prev().children().remove();
});

点击#first按钮,进入.closest() <td>,获得.prev()元素,这也是<td>,然后.remove().children()

这是要实现的一行。

     $(this).closest("td").prev().remove();