jQuery 更改子文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7415292/
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 change child text
提问by kamil
I have a jquery function that changes a text inside a element using a jquery "text" function. Inside this td element is child "a" tag like this.
我有一个 jquery 函数,它使用 jquery“文本”函数更改元素内的文本。在这个 td 元素里面是这样的子“a”标签。
<td class="v3"><a href="somelink">text to change</a>
<td class="v3"><a href="somelink">text to change</a>
The text to change is identified by the td class. When I change the text I lose the link. Question is how do I change the text using the parent element without touching the child (a href)?
要更改的文本由 td 类标识。当我更改文本时,我丢失了链接。问题是如何使用父元素更改文本而不触及子元素(a href)?
Thanx
谢谢
回答by Vlad Nicula
If you have:
如果你有:
<td class="v3">
<a href="somelink">text to change</a>
</td>
Then in your function you should have something like this:
然后在你的函数中你应该有这样的东西:
$("td.v3").children("a").text("new text");
However, this will select all links that are direct children of tds with class .v3. Adding a .first() after children should help:
但是,这将选择属于 .v3 类的 tds 的直接子级的所有链接。在孩子之后添加 .first() 应该会有所帮助:
$("td.v3").children("a").first().text("new text");
回答by Tim
Wrap the text in a span
element, and change the text in the span.
将文本包裹在一个span
元素中,并在跨度中更改文本。
<div id="foo">
<span>bar</span>
<a href="#">link</a>
</div>
...
$('#foo span').text('new text');
Edit:
编辑:
Or use $('td.v3 a').text("new text")
to change the text in the anchor, if that's what you want to do.
或者用于$('td.v3 a').text("new text")
更改锚中的文本,如果这是您想要做的。
回答by Tejs
You would simply change another element's text.
您只需更改另一个元素的文本。
<td>
<a href="#">Link</a>
<span>SomeText</span>
</td>
Then invoke like so:
然后像这样调用:
$('td').find('span').text('myNewText');
回答by CG_DEV
If you want to change text in a select menu, you can do this by giving an option an id or class.
如果要更改选择菜单中的文本,可以通过为选项提供 id 或类来实现。
$('selector').children('option[id=option_id]').text('new text');