在JS / JQuery中通过DOM获取BR分隔文本? [英] getting BR-separated text via DOM in JS/JQuery?

查看:472
本文介绍了在JS / JQuery中通过DOM获取BR分隔文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个greasemonkey脚本,用于解析具有以下一般结构的页面:

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>

我特意试图抓住(标题)部分。但是,您可以看到,只有一个< BR> 标签,没有自己的ID,只是一个<$ c的文本的一部分$ c>< CENTER> 标签,该标签具有与其相关联的其他文本的全部筏子。

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.

m做的是获取中心标签的innerHTML并使用正则表达式来匹配 /< br>([A-Za-z] *)< p>< b> ;统计/ 。对我来说这是很好的工作,但感觉就像有一个更好的方式来选择那个特定的文本。

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? :-)

推荐答案

编辑:更新以删除空格

var title = $('table center').contents().filter(function() {
         if( this.nodeType == 3 && $.trim(this.data) != "") { //get only text nodes and filter out whitespace elements
           return true;
        }
      }).get(2); // get the 3rd text node 


    alert( title.data ); // alerts "(Title)
    title.data = "How to use jQuery"; // (Title) changes

如何工作:

该函数通过提供的节点中的所有节点运行,在这种情况下,该中心标记为文本nodeType 3,所以你会得到一个数组,你的例子中有关闭的中心标记错位,所以这可能会给你错误,但我想你得到的想法(我想你最后失踪了)

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 )

您可以随时:

  $('table center').contents().filter(function() {
       if( this.nodeType == 3 && $.trim(this.data) != "") { //get only text nodes and filter out whitespace elements
           return true;
        }
      }).wrap('<p></p>') // make those text nodes paragraphs
      .end().filter('br')
        .remove(); // remove the brs

请参阅 jquery docs on .contents()

这篇关于在JS / JQuery中通过DOM获取BR分隔文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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