:contains()不返回预期的节点

时间:2014-09-01 21:25:11

标签: jquery replace greasemonkey

请考虑以下代码:

// @include     /(^https?:\/\/www\.|^https?:\/\/)google\.com(\.|\/).*/
// @include     /(^https?:\/\/www\.|^https?:\/\/)stackoverflow\.com\/.*/
// @include     /(^https?:\/\/www\.|^https?:\/\/)userscripts-mirror\.org\/.*/
// @include     http://wiki.greasespot.net/*
// @version     1.0
// @require     https://code.jquery.com/jquery-2.1.1.min.js
// @grant       GM_addStyle


$ ( 'body:contains("serscripts.org")').each ( function ()  {

var results = $(this);
var text = results.text();
console.log(text);
text = text.replace( /serscripts\.org/ig, "serscripts-mirror.org" );
text = text.replace( /(:8080|%3A8080)/ig, "");
    //results.text ( text );

} );

我预计返回应该只是包含该字符串的元素,但控制台上的结果是正文的所有文本。


在第:

行考虑this page
// @updateURL       https://userscripts.org/scripts/so...

我想改变它。


this one

// @require http://userscripts.org/scripts/source...

我也想改变。


应检查标签之间的所有单词是否为字符串,并仅返回包含该字符串的单词。

什么是正确的选择器?


注意
<a></a>之间的链接属性和文字已使用类似的.each ( function )更改。

1 个答案:

答案 0 :(得分:2)

:contains正在返回预期的内容。来自the spec

  

匹配文字可直接显示在所选元素中,元素的后代其组合中的任何一个


通常,要在网页上替换,换行或突出显示文本字词,您需要在单个TEXT_NODE级别工作。其他任何事都有可能造成垃圾:URL,ID,事件处理程序等等。

您可以使用Tree Walker

var txtWalker   = document.createTreeWalker (
    document.body,
    NodeFilter.SHOW_TEXT,
    {   acceptNode: function (node) {
            //-- Skip whitespace-only nodes
            if (node.nodeValue.trim() )
                return NodeFilter.FILTER_ACCEPT;

            return NodeFilter.FILTER_SKIP;
        }
    },
    false
);
var txtNode     = null;

while (txtNode  = txtWalker.nextNode () ) {
    var oldTxt  = txtNode.nodeValue;
    var newTxt  = oldTxt.replace (/serscripts\.org/ig, "serscripts-mirror.org");
    newTxt      = newTxt.replace (/(:8080|%3A8080)/ig, "");

    txtNode.nodeValue = newTxt;
}

这将安全地处理页面上的所有内容,但hrefsrc等HTML属性除外。

如果您希望更改这些代码,请使用单独的,有针对性的.each ()代码 - 就像您说的那样 - 但不要更改<a></a>之间的文本,因为已经完成了树步行者。

相关问题