0

我希望能够将我选择的任何单词链接到特定的 URL,例如:我希望单词“goat”链接到整个网站的“ http://goat.com ”。因此,所有“goat”/s 都将链接到整个网站的那个 URL。

我正在使用 wordpress,但我还没有找到一个插件来做到这一点。如果我能找到解决方案,我很可能会为此功能创建一个插件。

我知道如何在单个页面上定位一个单词。但我希望它跨越所有页面和这些页面中的所有单词(我为此使用了 JavaScript)。

4

3 回答 3

4

像这样的东西可能对你有用。

function replaceWithUri(textToReplace, element){
    element.innerHTML = element.innerHTML.replace(textToReplace, '<a href="http://www.' + textToReplace + '.com" >' + textToReplace + '</a>');
}

replaceWithUri('goat', document.getElementsByTagName('body')[0]);
于 2014-09-23T11:33:42.147 回答
1

这是一个糟糕的解决方案,但总比没有好:

我在这里找到了一些代码,它在整个页面中搜索一个世界,所以我复制粘贴并修改了它。

replaceWord 变量不能包含与 word 相同的字符串,否则会无限循环。

var word = " goat",
    replaceWord = " <a href = 'http://goat.com'>goat</a>",
    queue = [document.body],
    curr
;
while (curr = queue.pop()) {
    if (!curr.textContent.match(word)) continue;
    for (var i = 0; i < curr.childNodes.length; ++i) {
        switch (curr.childNodes[i].nodeType) {
            case Node.TEXT_NODE : // 3
                if (curr.childNodes[i].textContent.match(word)) {
                    curr.innerHTML = curr.innerHTML.replace(word,replaceWord);
                }
                break;
            case Node.ELEMENT_NODE : // 1
                queue.push(curr.childNodes[i]);
                break;
        }
    }
}
Hello goat

<div>Look a goat</div>

于 2014-09-23T11:40:54.090 回答
1

这可能会占用一些资源,并且 replaceWord 不能包含与 word 相同的字符串,否则它将永远循环。

document.onload = function() {
    var word = " goat",
        replaceWord = " <a href = 'http://goat.com'>goat</a>";

    while(document.body.innerHTML.indexOf(word) !== -1) {
        document.body.innerHTML = document.body.innerHTML.replace(word,replaceWord);
    }
}
Hello goat

<div>Look a goat</div>

于 2014-09-23T11:57:32.860 回答