在 JS/JQuery 中通过 DOM 获取 BR 分隔的文本?
我正在编写一个greasemonkey脚本,该脚本正在解析具有以下一般结构的页面:
<table>
<tr><td><center>
<b><a href="show.php?who=IDNumber">(Account Name)</a></b>
(#IDNumber)
<br> (Rank)
<br> (Title)
<p>
<b>Statistics:</b>
<br>
<table>
<tr><td>blah blah etc.
</td></tr></table></center></table>
我特别试图从中获取(标题)部分。然而,正如您所看到的,它仅由
标记引发,没有自己的 ID,只是
文本的一部分code> 标签,并且该标签有大量与其关联的其他文本。现在我正在做的就是获取 Center 标签的innerHTML,并在其上使用正则表达式来匹配 /
([A-Za-z ]*)
< ;b>统计/
。这对我来说没问题,但感觉必须有更好的方法来从中挑选出特定的文本。
……那么,有没有更好的办法呢?或者我应该向网站程序员抱怨他需要使该文本更易于访问? :-)
I am writing a greasemonkey script that is parsing a page with the following general structure:
<table>
<tr><td><center>
<b><a href="show.php?who=IDNumber">(Account Name)</a></b>
(#IDNumber)
<br> (Rank)
<br> (Title)
<p>
<b>Statistics:</b>
<br>
<table>
<tr><td>blah blah etc.
</td></tr></table></center></table>
I'm specifically trying to grab the (Title) part out of that. As you can see, however, it's set off only by a <BR>
tag, has no ID of its own, is just part of the text of a <CENTER>
tag, and that tag has a whole raft of other text associated with it.
Right now what I'm doing to get that is taking the innerHTML of the Center tag and using a regex on it to match for /<br>([A-Za-z ]*)<p><b>Statistics/
. That is working okay for me, but it feels like there's gotta be a better way to pick that particular text out of there.
... So, is there a better way? Or should I complain to the site programmer that he needs to make that text more accessible? :-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
编辑:更新以删除空格
工作原理:
该函数在提供的节点中的所有节点上运行,在本例中是中心标记。文本是nodeType 3,因此您将获得这些文本的数组。您的示例的结束中心标签放错了位置,因此可能会给您带来错误,但我认为您明白了。 (我认为您之前缺少 a )
您始终可以:
参见 jquery 文档 。内容()
EDIT: updated to remove whitespace
How it works:
The function is run through all of the nodes in the provided node, in this case that's the center tag. Text is nodeType 3, so you'll get an array of those. Your example has the closing center tag misplaced, so that might give you errors but I think you get the idea. (i think you're missing a at the end of that before )
You could always:
see the jquery docs on .contents()
这似乎有效:
This seems to work: