简体   繁体   English

通过 jquery 添加和删除 html 元素

[英]Add and remove html element by jquery

How can I add new <tr> after a clicked <tr> .如何在单击 <tr <tr>后添加新的 < <tr> On click of this <tr> and remove now created when click other <tr> (with repeat 1st scenario) by jQuery?单击此<tr>并在单击 jQuery 的其他<tr> (重复第一种情况)时创建删除?

I tried like this, but it does not work:我试过这样,但它不起作用:

 $("#test_table tr").click(function() { $(this).prev().remove(); $(this).closest('tr').append('<tr><td>2.2</td></tr>'); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table id="test_table"> <tr> <td>1</td> </tr> <tr> <td>2</td> </tr> <tr> <td>3</td> </tr> </table>

Given your goal it seems that you want to replace the current tr with the new HTML snippet.鉴于您的目标,您似乎想用新的 HTML 片段替换当前的tr To do that you just need to call after() to insert the new HTML, then remove() to clear the original tr :为此,您只需要调用after()来插入新的 HTML,然后remove()以清除原始tr

 $("#test_table tr").click(function() { $(this).after('<tr><td>2.2</td></tr>').remove(); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table id="test_table"> <tr> <td>1</td> </tr> <tr> <td>2</td> </tr> <tr> <td>3</td> </tr> </table>

However, as the only effect of this is to change the text within the td , you can just call text() instead:但是,这样做的唯一效果是更改td中的文本,您可以调用text()代替:

 $("#test_table tr").click(function() { $(this).find('td').text('2.2'); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table id="test_table"> <tr> <td>1</td> </tr> <tr> <td>2</td> </tr> <tr> <td>3</td> </tr> </table>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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