简体   繁体   中英

How can i print variable to formatted html in the javascript?

How can I print variable to formatted html in the javascript?

I would like to display as a hyperlink:

我想显示为超链接

The result i would like to have:

test

-------Code---------

This is the javascript function code:

function fetchComments(leaveRequestId) {

    $('#existingComments').html(lang_Loading);
    params = 'leaveRequestId=' + leaveRequestId;
    $.ajax({
        type: 'GET',
        url: getCommentsUrl,
        data: params,
        dataType: 'json',
        success: function(data) {                

            var count = data.length;
            var html = '';
            var rows = 0;

            $('#existingComments').html('');  
            if (count > 0) {
                html = "<table class='table'><tr><th>"+lang_Date+"</th><th>"+lang_Time+"</th><th>"+lang_Author+"</th><th>"+lang_Comment+"</th></tr>";
                for (var i = 0; i < count; i++) {
                    var css = "odd";
                    rows++;
                    if (rows % 2) {
                        css = "even";
                    }
                    var comment = $('<div/>').text(data[i]['comments']).html();
                    html = html + '<tr class="' + css + '"><td>'+data[i]['date']+'</td><td>'+data[i]['time']+'</td><td>'
                        +data[i]['author']+'</td><td>'+comment+'</td></tr>';
                }
                html = html + '</table>';
            } else {

            }
            $('#existingComments').append(html);
        }
    });
}

This should work.

 document.getElementById("displayed").innerHTML = document.getElementById("displayed").innerHTML.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
 <code id="displayed"><a href="#">test</a></code> <button onclick="document.getElementById('displayed').innerHTML = '<a href=\'#\'>test</a>'">Click To Change Into Hyperlink</button>

References

See Display HTML snippets in HTML for more information on displaying html on webpages.

I am also not sure what exactly you want, but I think you want to add some anchor tag using JavaScript and it should be rendered as HTML code, not as plain text.

Then you can do it like this.

 <.DOCTYPE html> <html> <body> <div id="demo"> </div> <button onclick="myFunction()"> Click here </button> <script> function myFunction() { document.getElementById("demo");innerHTML = '<a href="#">Test</a>'; } </script> </body> </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM