jQuery 在某个元素之前添加元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9475489/
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
add element before some element
提问by vinanghinguyen
I have this code:
我有这个代码:
<td>
<div id="vB_Editor_QR_cmd_email" class="imagebutton">
abc
</div>
</td>
I want put another element to this code like this:
我想在这个代码中添加另一个元素,如下所示:
<p>blablablalblablab</p>
<td>
<div id="vB_Editor_QR_cmd_email" class="imagebutton">
abc
</div>
</td>
I use this code
我用这个代码
$("#vB_Editor_QR_cmd_insertimage").before("<p>blablablalblablab</p>");
but it only put before div tag.
但它只放在 div 标签之前。
<td>
<p>blablablalblablab</p>
<div id="vB_Editor_QR_cmd_email" class="imagebutton">
abc
</div>
</td>
I want it like this
我想要这样
<p>blablablalblablab</p>
<td>
<div id="vB_Editor_QR_cmd_email" class="imagebutton">
abc
</div>
</td>
采纳答案by Anil D
Try this,
尝试这个,
$("#vB_Editor_QR_cmd_insertimage").parents("td:first").before("<p>blablablalblablab</p>");
parents("td:first") will return first parent of div
parent("td:first") 将返回 div 的第一个父级
hope this help.....
希望这有帮助.....
回答by James Montagne
Use beforeor insertBeforeto place an element before another.
使用before或insertBefore将一个元素放在另一个元素之前。
$("<p>blablablalblablab</p>").insertBefore("td");
or
或者
$("td").insertBefore("<p>blablablalblablab</p>");
or more specifical to your html:
或更具体到您的 html:
$("vB_Editor_QR_cmd_email").parent("td").before(...);
Though unless this is just a (bad) example, this is invalid. You can't have a <p>
tag directly before a <td>
because that would imply that the <p>
is within a <tr>
.
尽管除非这只是一个(坏)例子,否则这是无效的。您不能在 a<p>
之前直接添加标签,<td>
因为这意味着 the <p>
is 在 a 内<tr>
。
回答by Greg Franko
This selects the td element that has a nested div with an id of vB_Editor_QR_cmd_insertimage. It also provides a cleaner way to create an html element (that jQuery provides)
这将选择具有 id 为 vB_Editor_QR_cmd_insertimage 的嵌套 div 的 td 元素。它还提供了一种更简洁的方式来创建 html 元素(jQuery 提供)
$("div#vB_Editor_QR_cmd_insertimage").closest("td")
.before($("<p/>", { text: "blablablalblablab" }));