我正在尝试编写一个脚本来循环单词并向每个未链接的单词添加 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);
}); :
但我需要所有非链接词。
最佳答案
试试这个:
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>"));
}
关于javascript - 遍历单词并添加 'a' 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26664216/