用链接替换该文本? [英] Replace text with link to that text?

查看:74
本文介绍了用链接替换该文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我先前问题的跟进.我正在尝试使用Greasemonkey将<td>中的文本更改为包含该文本的链接.

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.

因此页面包含

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

我想使用Greasemonkey将其更改为:

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?

推荐答案

忘记jQuery,它只会降低您的页面速度. 我还没有真正测试过这段代码,但是它应该可以通过一些调试工作:

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

这篇关于用链接替换该文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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