将字符串转换为HTML - 将字符串转换为“ “href”元件 [英] Converting String to HTML - string to " a href" element
问题描述
您好我在将一些HTML链接添加到我的HTML页面时遇到了一些麻烦。我试过四处搜索但到目前为止没有任何帮助。
Hello I am having some trouble getting some HTML links to add to my HTML page. I have tried searching around but nothing has helped thus far.
我的页面最初会加载一个片段:
My page will initially load a snippet:
<div style="display: inline-block; color: rgb(0, 255, 144)">Roster: </div>
<span id="teamRoster"></span>
<br />
在视图中显示为 Roster:
现在我的代码片段已被修改为添加名称:
Right now my snippet has been modified to add names:
var rosterListings = "";
for (var i = 0; i < teamRoster.length; i++) {
rosterListings = rosterListings + teamRoster[i] + ", ";
}
$("#teamRoster").text(rosterListings);
这会将我的视图更新为名册:John,Frank,Susan等..
Which will update my View to Roster: John, Frank, Susan, ect..
但是,我现在尝试添加< a href>
标记在每个人周围,并将它们全部转换为实际链接。我的尝试看起来像这样
However, I am trying to now add <a href>
tag's around each person and turn them all into actual links. My attempt looks like this
var rosterListings = "";
for (var i = 0; i < teamRoster.length; i++) {
rosterListings = rosterListings + " <a href='" + idList[i] + "'>" + teamRoster[i] + "</a>,";
}
$("#teamRoster").text(rosterListings);
显示为
名册:< a href ='#'> John< / a>,< a href ='#'> Frank< / a> ;,等..
我理解为什么会发生这种情况,因为我正在设置实际的文本/字符串,但有没有办法将此字符串转换为HTML元素?我尝试了一些 $。parseHTML
我从谷歌搜索中找到的代码片段,但我必须将它们全部错误地实现.. :(
I understand why this occurring since I am setting actual text/strings, but is there a way to convert this string into HTML elements? I have tried a few $.parseHTML
code snippets that I found from Googling but I must be implementing them all wrong.. :(
感谢任何帮助,谢谢!
推荐答案
嗯,解决方案很明显
只需替换
$("#teamRoster").text(rosterListings);
使用:
$("#teamRoster").html(rosterListings);
因为如果你用它作为一个文本,然后它将它视为文本,如果你写html然后它会将其视为一个HTML
Because if you use it as a text then it will treat it as the text and if you write html then it will treat it as a html
这篇关于将字符串转换为HTML - 将字符串转换为“ “href”元件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!