我有以下文字:
var text = "hello @user1 and @user2 , how are you @user1 ?";
我想为所有以"@"开头的单词添加样式,并向它们添加单击事件以调用函数。 这是我的代码:
function findUsers(text) {
return text.match(/(?:^|W)@(w+)(?!w)/g);
}
function goToProfile(user) {
console.log("go to " + user + " profile.");
}
function addStyle(text) {
var users = findUsers(text);
if (users) {
for(var i = 0; i < users.length; i++) {
var user = users[i];
text = text.replace(user
, '<span style="color:blue;" onclick="goToProfile('' + user + '')">'
+ user + '</span>');
}
}// end if
return text;
}
此代码无法为第二个"@user1"添加样式,也无法将 Click 事件添加到单词中。 有没有更有效的方法可以做到这一点?
您需要从该方法返回的结果中删除重复项findUsers
而不是使用string.replace
使用string.replaceAll
,因为您已经具有唯一的用户值。 另外,您需要将 span 标记<span>
包装在锚标记<a>
中,以使其看起来像链接。 请仔细阅读下面的代码片段,该代码片段可以执行您想要伴随的操作。
function findUsers(text) {
return text.match(/(?:^|W)@(w+)(?!w)/g);
}
function goToProfile(user) {
console.log("go to " + user + " profile.");
}
function addStyle(text) {
var users = findUsers(text);
// this is where you need to remove duplicate from array
var uniqueusers = users.filter(function(item, i, ar) {
return ar.indexOf(item) === i;
});
if (uniqueusers) {
for (var i = 0; i < uniqueusers.length; i++) {
var user = uniqueusers[i].trim();
//wrapping span in anchor tag here and use replaceAll instead of replace.
text = text.replaceAll(user, '<a href=#><span style="color:blue;" onclick="goToProfile('' + user + '')">' +
user + '</span></a>');
}
} // end if
return text;
}
var text = document.getElementById('input1');
text.innerHTML = addStyle(text.innerText);
<div id='input1'>
"hello @user1 and @user2 , how are you @user1 ?";
</div>