Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
956 views
in Technique[技术] by (71.8m points)

javascript - Replace text with link to that text?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...