Converting String to HTML - string to “ a href” element

前端 未结 3 1882
星月不相逢
星月不相逢 2021-01-18 16:10

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

相关标签:
3条回答
  • 2021-01-18 16:17

    Well, solution is quite obvious

    Just replace

     $("#teamRoster").text(rosterListings); 
    

    With:

    $("#teamRoster").html(rosterListings);
    

    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

    0 讨论(0)
  • 2021-01-18 16:22

    The problem is that you're using .text(), which will insert only text into the span, as seen here.

    You need to use .html() if you want what is inserted to actually render as HTML.

    So, try this:

    $("#teamRoster").html(rosterListings);
    

    Demo

    Also note that the way you've set up your for loop causes an extra comma to be placed at the end of the list; I've fixed that here by checking whether it's the last element:

    if (i !== teamRoster.length - 1) {
            rosterListings = rosterListings + " <a href='" + idList[i] + "'>" + teamRoster[i] + "</a>,";
    } else {
            rosterListings = rosterListings + " and <a href='" + idList[i] + "'>" + teamRoster[i] + "</a>.";
    }
    
    0 讨论(0)
  • 2021-01-18 16:28

    As Just code points out, you want to use the html method, not the text method. html() is jQuery's wrapper for innerHTML, which injects the string as html.

    Here is a jsFiddle showing the difference:

    http://jsfiddle.net/89nxt/

    $("#teamRosterHtml").html("<a href='#'>John</a> <a href='#'>Frank</a>");
    $("#teamRosterText").text("<a href='#'>John</a> <a href='#'>Frank</a>");
    
    0 讨论(0)
提交回复
热议问题