概要: 由於以前的項目是angular開發(vue和react也是同樣),對其中的雙向數據綁定的使用感受很方便,而後就思考怎麼使用到jquery框架中來,適用於 列表生成html
知識點: 正則與其反向引用,str.replace vue
html部分node
<!--列表li 模板--> <script type="text/html" id="row"> <li> <h6 class="qa_title"><a href="qa_article.shtml?qid={{qid}}">{{title}}</a></h6> <div class="qa_info c"> <span><i class="icon icon_visit"></i>瀏覽:{{view_num}}</span> <span><i class="icon icon_commt"></i>回答:{{comoment_num}}</span> <span class="fr"><i class="icon icon_date"></i>提問時間:{{add_time}}</span> </div> </li> </script>
js部分,使用"\{\{(.+?)\}\}","igm",正則找到 $('#row') 下面的 {{}}包含的字段,react
tempLi.replace(reg, function (node, key) { return data.info[i][key]; });
將字段替換爲內容jquery
1 getHostList:function(){ 2 var request={} 3 request.page_type='get_hot_question_list'; 4 request.page_num='0'; 5 $.ajax({ 6 url: Fields.url+'question', 7 data: request, 8 dataType: "json", 9 type: 'post', 10 async: false, 11 success: function (result) { //成功後回調 12 if(result.ret==0){ 13 var data=result.info; 14 //列表數據 15 var reg = new RegExp("\{\{(.+?)\}\}","igm"); //匹配 {{}} 的內容 16 var tempLi = $("#row").html(); 17 var html=''; 18 for(var i=0;i<data.all_num-1;i++) { 19 if(!data.info[i])break; 20 html+= tempLi.replace(reg, function (node, key) { 21 return data.info[i][key]; 22 }); 23 } 24 $("#qa_hot_list").html(html); 25 }else{ 26 Func.popShow('#pop'); 27 $('#pop .jx_inf').text(result.info) 28 } 29 }, 30 error: function(e){ //失敗後回調 31 32 } 33 })
效果:ajax