选择第一级文本元素'.text()'而不选择子元素 [英] Selecting the first-level text element '.text()' without selecting child elements

查看:81
本文介绍了选择第一级文本元素'.text()'而不选择子元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下html

<label>
outer
<span>inner</span>
</label>

我想替换'外部'值,留下带有'内部'文本的span。使用

I want to replace the 'outer' value, leaving the span with its 'inner' text intact. Using

$('label').text('new outer');

替换标签的全部内容(以及跨度)。是否有一种漂亮的方法只选择文本块'outer'而不添加额外的跨度或执行高级的东西,比如存储标签内部跨度的值然后重新应用它?

replaces the entire content of the label (along with the span). Is there a nifty way to only select the text block 'outer' without adding extra spans or doing advanced stuff like storing the value of the label's inner span and then reapplying it?

推荐答案


有没有一种方法可以只选择文本块'outer'而不添加额外的跨度或执行高级的东西,比如存储标签内部跨度的值和然后重新申请?

Is there a nifty way to only select the text block 'outer' without adding extra spans or doing advanced stuff like storing the value of the label's inner span and then reapplying it?

不是真的。

可以使用正则表达式替换< span> 之前的所有内容,但它会是一个笨重的正则表达式,虽然它适用于某些情况,但它会破坏如果你有任何其他标记,特别是如果你有另一个元素包装< span>

You could use a regular expression to replace everything before <span>, but it would be a clunky regex, and while it would work for some cases, it would break if you had any other markup in there, especially if you had another element wrapping the <span>.

我的建议是简单地在那里放一个跨度。如果你知道你将要操作那段代码,那么在DOM中给它一个元素。这是让它易于理解的最佳方式,它让你远离做愚蠢的事情,比如重建整个结构只是因为你想改变一个单词。

My suggestion would be to simply put another span in there. If you know you're going to be manipulating that block of code, then give it an element in the DOM. That's the best way to make it easy to get at, and it gets you away from doing silly stuff like rebuilding the whole structure just because you wanted to change a single word.

这篇关于选择第一级文本元素'.text()'而不选择子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆