使用 JQuery 替换整个表行(包括 <tr></tr>)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11206355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:19:47  来源:igfitidea点击:

Replace entire table row (including <tr></tr>) using JQuery

jquery

提问by rwkiii

I've looked at other examples here, but they seem to be replacing the contents of a <tr>and not the entire row including the <tr>.

我在这里查看了其他示例,但它们似乎正在替换 a 的内容,<tr>而不是包括<tr>.

<table>
    <tr style="display:block">
        <td id="someid">Test</td>
        <td>Some text</td>
    </tr>
</table>

The following code seems to only replace the innerHTML of the <tr>. I need to replace everything, including the <tr>so that the row will collapse. Can anyone confirm that this code does or does not completely replace the row:

下面的代码似乎只替换了<tr>. 我需要替换所有内容,包括<tr>以便该行折叠。任何人都可以确认此代码是否完全替换了该行:

var newtr = "<tr style='display:none'><td id='someid'></td><td></td></tr>"
$("td#someid").parent().html(newtr);

The reason why I don't think the entire <tr>is being replaced is because the row doesn't collapse - though I have tested the HTML outside of JQuery and it works fine.

我不认为整个<tr>被替换的原因是因为该行没有折叠 - 尽管我已经在 J​​Query 之外测试了 HTML 并且它工作正常。

回答by Peter Olson

You're almost there, just use the jQuery replaceWith[jQuery docs]function:

大功告成,只需使用 jQuery replaceWith[jQuery docs]函数:

$("td#someid").parent().replaceWith(newtr);

回答by Jon

The proper function is .replaceWith:

正确的功能是.replaceWith

$("td#someid").parent().replaceWith(newtr);

回答by John Green

If you're trying to replace the object, not its contents:

如果您要替换对象,而不是其内容:

$("td#someid").parent().replaceWith(newtr);

回答by Adil

Use replaceWith method of jquery to replace the element.

使用jquery的replaceWith方法来替换元素。

$('#someid').parent().replaceWith(newtr);

回答by jaypeagi

If you prefer the HTML technique as opposed to switching out elements, try this:

如果您更喜欢 HTML 技术而不是切换元素,请尝试以下操作:

You are correct in saying that this will not replace the tr element. .html("...") replaces the inner HTML of the element (the tr in this case). Use the JavaScript outerHTML to achieve this: $("td#someid").parent().get(0).outerHTML = newtr;

您说这不会替换 tr 元素是正确的。.html("...") 替换元素的内部 HTML(在本例中为 tr)。使用 JavaScript outerHTML 来实现这一点:$("td#someid").parent().get(0).outerHTML = newtr;

回答by Ahsan Rathod

See this Demo: http://jsfiddle.net/rathoreahsan/QXmTN/

看到这个演示:http: //jsfiddle.net/rathoreahsan/QXmTN/

Jquery

查询

$("td#someid").parent().replaceWith(newtr);

回答by Umair Noor

you can also check this JsFiddle

你也可以检查这个JsFiddle

var newtr = "<tr style='display:none'><td id='someid'></td><td></td></tr>";

$("td#someid").parent().parent().html(newtr);