JQuery:获取不包括嵌套标记的标记内容 [英] JQuery: Get tag content excluding nested tags

查看:225
本文介绍了JQuery:获取不包括嵌套标记的标记内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些HTML如下:

I've got some HTML like the following:

<span id="A">Text I'm interested in
  <span id="B">Other crap I don't care about</span>
</span>

我想获得spanA的文本内容,不包括任何嵌套标记在上述示例中跨度B的内容)。我试图获取文本内容,而不是HTML内容。此外,在我的特定情况下,我知道在任何其他标签之前,在span A内总是会有一些文本,但我对较少约束的解决方案感兴趣。

I'm looking to get the text content of span "A" excluding any nested tags (i.e. the content of span "B" in the above example). I'm trying to get the text content, not the HTML content. Also, in my particular case, I know there will always be some text inside of span A prior to any other tags, but I'm interested in the less-constrained solution as well.

我考虑过的简单但笨重的方法只是做$(#A)。html(),然后解析,直到我点击一个非转义的<但是感觉像应该有一个更清洁的解决方案。

The simple-but-clunky approach I've considered going with is just doing $("#A").html() and then parsing through until I hit an unescaped "<" but it feels like there should be a cleaner solution.

推荐答案

我相当肯定没有内置的方式来做 - 虽然你可以寻找一个插件,它可能存在。有人发布了.text()方法(但删除了帖子),它会得到所有的文本,减去标签,这意味着你会得到文本我感兴趣的其他垃圾我不在乎 - 不是你想要的。

I'm fairly sure there's no built in way to do it - although you could look for a plugin, it may exist. Someone else posted the .text() method (but deleted the post) which will get you ALL the text, minus the tags, which means you'll get "Text I'm interested in Other crap I don't care about" -- not what you want.

EDIT

对此感兴趣,所以我花了一些时间。这是解决方案:)

Okay, I decided I was interested in this so I spent some time. Here's the solution :)

    copyOf = $('#A').clone();
    copysKids = copyOf.children();
    copysKids.remove();

    alert(copyOf.text());

我们正在做的是克隆你想要得到文本的节点 - 我们不想对原始操作,因为这将更改页面。然后,我们抓住所有子节点的集合,并令他们。剩余的文本是您要查找的文本。

What we're doing is making a clone of the node you're trying to get text out of - we don't want to operate on the original because this would change the page. Then we're grabbing a collection of all the child nodes, and nuking them. The remaining text is the text you were looking for.

这篇关于JQuery:获取不包括嵌套标记的标记内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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