首页 > 如何使用jquery插入大量html..

如何使用jquery插入大量html..


添加分类那里是用的ajax post来添加,我想添加成功后直接在左面的列表里里显示..但每个tr元素里的html非常多.

该如何插入比较方便


如果项目有用到seajs的话,可以试试seajs.text这个插件

    var html = require('./dataTable.html')
    $('#target').html(html)

补充一句,这种表格类型的数据你要么模版放后端循环输出,要么模版放前端 渲染/注入,静态页面遍历dom来更新效率太低。

至于什么事模版,推荐阅读这篇文章:http://ued.taobao.org/blog/2012/04/juicer-%E4%B8%80%E4%B8%AAjavascript%E6%A8%A1%E6%9D%BF%E5%BC%95%E6%93%8E%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%92%8C%E4%BC%98%E5%8C%96/(敢不敢加个短链接功能...)


准备html字符串

无论怎么插入,那堆html字符串肯定是省不了的……
所以你可以选择是把那堆html放在

<script type="text/template" id="tr-template">
</script>

然后用$('#tr-template').html()来获取。
还是直接作为Ajax的结果返回。

插入字符串

插入的话,用$(...).append(html)就能把字符串加入到目标元素中了。
不过貌似你还需要做一些替换(如果能直接插入就不成问题了对吧),还好有人写了个String.format函数

见 http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format/4673436#4673436 下面最高分的答案

所以你可以拷下来改改,用这个String.format将模板中的{1},{2}什么的替换成Ajax返回的变量,这样再插入就好了。

更进一步说,还可以拓展这个函数,提高它的可读性:

if (!String.prototype.format) {                                                 
  String.prototype.format = function() {                                        
    var hash = arguments[0];                                                                                       
    return this.replace(/{(\w+)}/g, function(match, item) {                        
      return typeof hash[item] != 'undefined' ? hash[item] : match;                
    });                                                                            
  };                                                                               
}                                                                                  

console.log("my name is {name}".format({ name: '顺其自然' }));

可以考虑使用 js模板引擎
淘宝的kissy template,腾讯的artTemplate,百度的baiduTemplate等;
或者国外的handlebarsjs等


http://plugins.jquery.com/jsontotable

【热门文章】
【热门文章】