Replace text with link to that text?

后端 未结 2 1493
太阳男子
太阳男子 2020-12-20 10:20

This is a follow up of my earlier question. I\'m trying to use Greasemonkey to change the text in a to a link that contains that text.

So the

相关标签:
2条回答
  • 2020-12-20 10:24

    Forget jQuery, it'll just slow your pages down. I haven't really tested this code, but it should work maybe with some debugging:

    // ==UserScript==
    // ==/UserScript==
    (function() { 
        // collect variables
        // you can change this to change which element you replace
        var reference = document.querySelector('td.something>div:first-child');
        var text = reference.innerText;
        var replacement = text.replace(reference, "www.somewhere.com/q?=" + reference);
    
        // create new anchor tag
        var a = document.createElement('a');
        a.href = replacement;
        a.innerText = text;
    
        // do the replacement
        reference.innerHTML = ''; // clear the old contents of the reference
        reference.appendChild(a); // append the new anchor tag into the element
    })();
    
    0 讨论(0)
  • 2020-12-20 10:39

    This is a fairly standard operation for a Greasemonkey script. jQuery's .wrapInner()Doc and waitForKeyElements()Example make it easy.

    Your complete script would look like this:

    // ==UserScript==
    // @name     _Select text (re)linker
    // @include  http://YOUR_SERVER.COM/YOUR_PATH/*
    // @require  http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
    // @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
    // @grant    GM_addStyle
    // ==/UserScript==
    /*- The @grant directive is needed to work around a design change
        introduced in GM 1.0.   It restores the sandbox.
    */
    waitForKeyElements (".something > div", linkifyText);
    
    function linkifyText (jNode) {
        jNode.wrapInner ( function () {
            var newHref = 'http:\/\/www.somewhere.com\/q?='
                        + encodeURIComponent (this.textContent.trim () );
    
            //-- Note that link text will be filled in automatically.
            var newLink = '<a href="' + newHref + '"></a>';
    
            return newLink;
        } );
    }
    
    0 讨论(0)
提交回复
热议问题