javascript - 用链接替换标签,它只替换字符串中的最后一个词

标签 javascript jquery

我正在尝试制作一个主题标签系统,所以我到达了编辑文本功能,如果用户键入主题标签词,我想用主题标签链接替换输入的编辑。所以我正在使用 JavaScript 和 jQuery 来执行此操作,但问题是 for 循环仅替换字符串中的最后一个单词,而不是所有带有链接的字符串。

// Turn hashtags into links
var discussionText = "#example #text #string #one #two #three #hashtag #word";
var wordsArray = discussionText.split(" ");

for (i = 0; i < wordsArray.length; i++) {
  console.log(i);
  if (wordsArray[i].indexOf('#') > -1) {
    var wordWithoutHashtag = wordsArray[i].replace("#", "");
    console.log(wordWithoutHashtag);
    $("#" + editDiscussionButtonId + "-" + editDiscussionButtonUserId + "-spanDiscussionEdit").html(function() {
      return $(this).text().replace(wordsArray[i], "<a href='search.php?sec=all&q=" + wordWithoutHashtag + "' class='hashtag_link'>" + wordsArray[i] + "</a>");
    });
  }
}

最佳答案

更改 html(function) 使用现有的 html 参数。当您使用 text()它不会返回之前的 <a>您在之前的循环迭代中创建的,只有 <a> 中的文本.

$(selector).html(function(index, existingHtml){
   return existingHtml.replace(wordsArray[i], ....
});

同样,如果您刚刚更改了 $(this).text().replace..$(this).html().replace...它会起作用。


更有效的方法是在循环之前获取现有内容一次,并对存储在变量中的字符串进行所有修改,然后在循环完成后替换修改后的内容一次

关于javascript - 用链接替换标签,它只替换字符串中的最后一个词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55313229/

相关文章:

javascript - Angular - 为什么 Number.isNaN 对于非空字符串返回 false?

jQuery Cycle 插件,所有图像加载并显示在开头

javascript - JS 弹出窗口的 CSS 动画淡出/淡入

javascript - jQuery urlencode/decode 补丁帮助

javascript - 使用 jQuery 追加多个项目

jquery - 在 ajax post 中发送二进制数据

javascript - jQuery:div 和 tbody 之间的查找行为不一致

javascript - 循环 .find() 结果并收集 .text()

javascript - jQuery foo.html ("<span>bar</span>") 没有改变 foo[0],那么它是什么意思呢?

javascript - 如何让ajax显示表格列表而不点击文本字段