我正在尝试制作一个主题标签系统,所以我到达了编辑文本功能,如果用户键入主题标签词,我想用主题标签链接替换输入的编辑。所以我正在使用 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/