开发者

What is the correct concatenation approach in Javascript?

开发者 https://www.devze.com 2023-04-04 18:29 出处:网络
I\'ve searched the internet and people suggest using array\'s then doing arr.join() but then some argue it\'s slower in firefox, what the correct method?

I've searched the internet and people suggest using array's then doing arr.join() but then some argue it's slower in firefox, what the correct method?

$.each(data.rows, function (i) {
        var row = data.rows[i];
        var htmlRow = '<div class="colour"><img src="开发者_高级运维' + row[3] + '" alt="' + row[1] + '" /><span>' + row[1] + '</span> <input type="hidden" value="' + row[4] + '"/></div>';

        htmlRow = htmlRow + '<div class="products">';
        for (var k = 6; k < row.length; k++) {

            htmlRow = htmlRow + $('#product').jqote(row[k], '*');
        }
        htmlRow = htmlRow + '</div>';
        $('.body-holder').append('<div class="holder">' + htmlRow + '</div>');
    });

Thanks


I would recommend using a template engine such as tmpl() from jquery. It is probably not faster than what you are doing but the performance differences are trivial. That way of building html(as you are doing) will probably get really ugly fast without a proper templating tool.


Dan is right, using jQuery Templates is the way to go. Here is some sample code to help you understand just how much more powerful it is:

<!-- SAMPLE TEMPLATE -->
<script id="myTemplate" type="text/html">
    <li class="activity exceptionManager-observation">
        <hr />
        <table>
            <tr>
                <td valign="top">
                    <img class="icon" src="Includes/Images/symbol_error.png" alt="" border="0" />
                </td>
                <td align="left" valign="top">
                    <div class="date">${Date}</div>
                    <div class="rank">${ProjectNumber}</div>
                    <div class="message">${Message}</div>
                </td>
            </tr>
        </table>
    </li>
</script>

<script type="javascript">        
var record = {ProjectNumber: '1234', Message: 'This is my rifle! This is my gun!'};

/// <summary>Append's a record into the UI.</summary>    
function Append(record) {
    try {
        var template = $('#myTemplate').tmpl(record);
        template.prependTo('#someListInMyPage');
    }
    catch (err) {
        alert(err);
    }
}
</script>
0

精彩评论

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

关注公众号