简体   繁体   中英

How to remove the content in the td tag using jquery

I have a table defined like

<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();
});

How can i remove the previous element in the td . But i don't want to remove the td

If you want to remove the complete contents of that previous TD (rather than a specific INPUT element), this will work:

$(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("");
});

This will remove all content in previous td tag.

You should go up the DOM tree until parent <td> , then get previous <td> , find <input> inside and remove it. You should use on() with event delegation instead of deprecated live() :

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

Note, that instead of document you may use any other static parent element of #first .

这是实现的一个班轮。

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

I suggest you to use .on() instead because .live() is been now removed from the jQuery version 1.9+:

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

Click the #first button and get to the .closest() <td> and get the .prev() element which is a <td> as well then .remove() its .children() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM