我正在尝试编写一个脚本来循环单词并将href链接添加到每个非链接的单词。
示例:
<body>
something
<a href = "anything"> Blaba </a>
<p>Some words</p>
Something else
</body>
将是:
<body>
<a href= "added link" > something< /a>
<a href = "anything"> Blaba </a>
<p><a href= "added link" > Some< /a> <a href= "added link" > words< /a></p>
<a href= "added link" > Something< /a> <a href= "added link" > else< /a>
</body>
我只到达了包装函数
function Replacer(x){
var str = $(x).text();
var words = str.split(" ");
var inner = " ";
var wordsLength = words.length;
for (var i = 0; i < wordsLength; i++) {
dict_url = 'http://' + language + '.kasahorow.org/app/d?kw='+ words[i] + '&fl='+ language +'&tl=en';
final_line = '<a href="' + dict_url+ '" >' + words[i] + " </a>";
inner = inner + final_line
}
$(x).replaceWith(inner);
}
当我使用类似的东西
时,它可以正常工作 $('p').each(function(){
Replacer(this);
}); :
但我需要所有非链接词。
答案 0 :(得分:0)
循环子节点,仅替换文本节点。由于显而易见的原因,跳过a
个节点。
function ReplaceText(x)
{
var str = x.textContent;
var words = str.split(" ");
var wordsLength = words.length;
var parent = x.parentNode;
for (var i = 0; i < wordsLength; ++i) {
dict_url = 'http://lang.kasahorow.org/app/d?kw='+ words[i] + '&fl=lang&tl=en';
var a = document.createElement('a');
a.setAttribute('href', dict_url);
a.innerHTML = words[i];
parent.insertBefore(a, x);
parent.insertBefore(document.createTextNode(' '), x);
}
parent.removeChild(x);
}
function Replacer(x){
var kids = x.childNodes;
for ( var j = kids.length - 1; j >= 0; --j )
{
if (kids[j].nodeType == 3)
ReplaceText(kids[j]);
else if (kids[j].tagName.toLowerCase() != "a")
Replacer(kids[j]);
}
}
Replacer(document.body);
something
<a href = "anything"> Blaba </a>
<p>Some words</p>
Something else
答案 1 :(得分:0)
试试这个:
fuction makeLinks(language){
$(document).contents().filter(function(){
return this.nodeType === 3;
}).replaceWith($(this).text().replace(/\b(.+)\b/, "<a href='http://"+language+".kasahorow.org/app/d?kw=$1'>$1</a>"));
}