Replace text with link to that text?

主宰稳场 提交于 2019-11-28 12:56:23

问题


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

So the page contains

<td class="something"><div style="width: 200px;">
  randomtext
</div></td>

And I want to change it using Greasemonkey to:

<td class="something"><div style="width: 200px;">
  <a href="www.somewhere.com/q?=randomtext">randomtext</a>
</div></td>

So far, I've cobbled together this little bit of code, but I'm sure it's the wrong approach as I'm not getting anywhere:

// ==UserScript==
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js
// ==/UserScript==
(function() { 
    var reference = document.getElementsByTagName('something')
    var replacement = reference.replace(reference, "www.somewhere.com/q?=" + reference)
    document.getElementById("user-reference-value").innerHTML = replacement;
})();

What more do I need to do to make this work?


回答1:


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
})();



回答2:


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;
    } );
}


来源:https://stackoverflow.com/questions/27905306/replace-text-with-link-to-that-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!