如果我有这样的 html:
<li id="listItem">
This is some text
<span id="firstSpan">First span text</span>
<span id="secondSpan">Second span text</span>
</li>
我正在尝试使用 .text()
来检索字符串“This is some text”,但如果我说 $('#list-item') .text()
,我得到“这是一些 textFirst span textSecond span 文本”。
有没有办法只获取(并可能通过 .text("")
等方式删除)标签内的自由文本,而不是其子标签内的文本?
HTML 不是我写的,所以这是我必须处理的。我知道在编写 html 时将文本包装在标签中会很简单,但同样,html 是预先编写的。
最佳答案
我喜欢这个基于 clone()
方法的可重用实现here仅获取父元素内的文本。
提供代码以方便引用:
$("#foo")
.clone() //clone the element
.children() //select all the children
.remove() //remove all the children
.end() //again go back to selected element
.text();
关于jquery - 使用 .text() 仅检索未嵌套在子标签中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39959005/