开发者

which is better way of building html using jquery

开发者 https://www.devze.com 2023-04-11 05:10 出处:网络
I am currently creating html ul in this way. First I am making an html variable. Then I am appending li to this html variable. Now I do not know whether this is a better way or not. While searching ab

I am currently creating html ul in this way. First I am making an html variable. Then I am appending li to this html variable. Now I do not know whether this is a better way or not. While searching about this I came across this $(document.createElement('div'));. Is there any other better way? Please I need reason why my current approach is not good or good and why the other approach which I should follow is better than this?

function newsfeed(u开发者_StackOverflow社区serid, username, msg, date_time) {
    var url = "https://graph.facebook.com/" + userid + "/picture";
    //var limit = 80;
    if(typeof(msg) != "undefined" && msg != "") {
        html += "<div class='container'>";
        html += "<li class='profile_image'><img src='" + url + "' /></li>";
        html += "<li class='from_name'>" + short_msg(username, true) + "</li>";
        html += "<li class='message'>" + short_msg(msg, false) + "</li>";
        html += "<li class='time_ago'>" + relative_time(date_time) + "</li>";
        html += "<li class='no_float'></li>";
        html += "</div>";
    }

    return html;
}


AFAIK, creating DOM elements the way you do, is the best one, when using jQuery. There's some explanation here:

http://www.learningjquery.com/2009/03/43439-reasons-to-use-append-correctly


Use jQuery.tmpl(). For example:

<script id="tpl1" type="text/x-jquery-tmpl">
    <div class="container">
        <li class="profile_image"><img src="${url}" /></li>
        <li class="from_name">${username}</li>
        <li class="message">${msg}</li>
        <li class="time_ago">${date_time}</li>
        <li class="no_float"></li>
     </div>
</script>
<script type="text/javascript">
    function newsfeed(userid, username, msg, date_time) {
        var url = "https://graph.facebook.com/" + userid + "/picture";
        //var limit = 80;
        if(typeof(msg) != "undefined" && msg != "") {
            var $html = $('#tpl1'),tmpl({
                url: url,
                username: short_msg(username, true),
                msg: short_msg(msg, false),
                date_time: relative_time(date_time),

            }); 
            return $html.html();
        }
    }
</script>

Besides the improved readability (you can use syntax highlight tools on the HTML snippet etc.) this will html-encode your variables and give some protection against XSS attacks. (You should still encode the URL manually, though.)

0

精彩评论

暂无评论...
验证码 换一张
取 消