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

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

问题描述

我有以下html

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

我要替换外部"值,使跨度完整保留其内部"文本.使用

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

$('label').text('new 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?

推荐答案

是否有一种仅选择文本块外部"而不增加额外跨度或进行高级操作(如存储标签内部跨度的值然后重新应用)的好方法?

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.

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

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