Javascript jQuery - 仅设置元素的文本而不删除其他元素(锚点)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6156470/
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
jQuery - setting an element's text only without removing other element (anchor)
提问by J.C. Inacio
I have an element like this:
我有一个这样的元素:
<td>
<a>anchor</a>
[ some text ]
</td>
And i need to set it's text in jQuery, without removing the anchor.
我需要在 jQuery 中设置它的文本,而不删除锚点。
The element's contents could vary in order (text before or after), and the actual text is unknown.
元素的内容顺序可能会有所不同(文本之前或之后),实际文本未知。
Thanks
谢谢
New Update
新更新
This is what i came up using, assumes only a single text node:
这是我想出来的,假设只有一个文本节点:
function setTextContents($elem, text) {
$elem.contents().filter(function() {
if (this.nodeType == Node.TEXT_NODE) {
this.nodeValue = text;
}
});
}
setTextContents( $('td'), "new text");
回答by Juan Mendes
Neal's answeris my suggestion. jQuery doesn't have a way to select text nodes How do I select text nodes with jQuery?.
尼尔的回答是我的建议。jQuery 没有选择文本节点的方法如何使用 jQuery 选择文本节点?.
Changing your HTML structure will make for the simplest code. If you can't do it, you can just use the childNodes property looking for nodes of type 3 (TEXT_NODE)
更改您的 HTML 结构将使代码变得最简单。如果你不能这样做,你可以使用 childNodes 属性寻找类型 3 (TEXT_NODE) 的节点
Here's some sample code that assumes the last node is the node you want to edit. This is a better approach than replacing the entire contents of the td because you could lose event handlers when you recreate the HTML
下面是一些示例代码,假设最后一个节点是您要编辑的节点。这是比替换 td 的全部内容更好的方法,因为在重新创建 HTML 时可能会丢失事件处理程序
$('a').click(() => console.log('<a> was clicked'))
$('#btn').click(() =>
$('.someClass').get(0).lastChild.nodeValue = " New Value");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='someClass'>
<a href="javascript:void(0)">anchor</a> [ some text ]
</div>
<button id='btn'> Change text without losing a tag's handler</button>
回答by Naftali aka Neal
If it is possible to put the text in a span:
如果可以将文本放在跨度中:
<td id='someID'>
<a>anchor</a>
<span>[ some text ]</span>
</td>
You can do:
你可以做:
$('td#someID span').text('new text')