javascript - 遍历单词并添加 'a' 标签

标签 javascript jquery html wrapper words

我正在尝试编写一个脚本来循环单词并向每个未链接的单词添加 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/

相关文章:

javascript - express.js 以任意顺序链式路由

javascript - 使用传单 map 上的按钮更改标记文本

jquery - 只有点击的 div 应该有不同的颜色

javascript - Textarea自动高度,页面刷新时保持高度不变

javascript - 尝试循环出nodeJS中的旧日志仍然会写入循环出的文件

javascript - 如何使用 javascript 制作与轻量级图表相同的图表

javascript - 如何随着时间的推移改变 CSS 样式并专注于元素?

php - 在附加的 <li> 元素上添加工具提示不起作用

css - Bootstrap 中的图标行

javascript - file.files[0] 无法读取未定义的属性 '0'