在頁面中使用拼接字符串的方式顯示動態加載的數據


在做頁面的時候為了使頁面美化,我們經常會用拼接字符串的方式,動態加載后台的數據,這里我們使用的前台框架是bootstrap,但是很多效果還是要用jquery來實現

(1)方法傳參與字符串的拼接  (拼接用的replace)

         先聲明一個展示數據的頁面模型(使用過的模型1)

var userModel = "<div class=\"itemdiv commentdiv\" style=\"margin-left: 7%;\">"+
"<div class=\"row text-left\" style=\"margin-top:5px;\">"+
"<label style=\"color: #737D81;\">用戶ID:</label>"+
"<label>&nbsp;&nbsp;{userid}</label>"+
"</div>"+
"<div class=\"row text-left\" style=\"margin-top:5px;\">"+
"<label style=\"color: #737D81;\">姓名:</label>"+
"<label>&nbsp;&nbsp;{username}</label>"+
"<button id=\"{btnId}\" class=\"btn btn-sm btn-info\" style=\"height:30px;margin-left: 20%;\">添加</button>"+
"</div>"+
"<div class=\"row text-left\" style=\"margin-top:5px;\">"+
"<label style=\"color: #737D81;\">電話:</label>"+
"<label>&nbsp;&nbsp;{telephone}</label>"+
"</div>"+
"<div class=\"row\">"+
"<div class=\"hr hr8\"></div>"+
"</div>"+
"</div>";

        然后ajax加載后台數據,然后使用replace,將數據動態替換到頁面模型中

$.ajax({
url:'<%=basePath%>platform/getUserPad.action',
type : 'POST',
dataType : 'json',
data :{
user_number : $("#form_searchSecurity").val(),
user_name : $("#search_user_name").val(),
},
success : function(data) {


$.each(data, function(index, element) {

    //此處替換頁面模型中的值
var oneUserInfo = userModel.replace(/{userid}/g,element.userid).replace(/{username}/g,element.username)
.replace(/{telephone}/g,element.telephone)
.replace(/{btnId}/g,'btnId'+index);         //給button設置動態ID,不需要可不設置


$("#userModelDiv").append(oneUserInfo);   //將頁面中的值替換好之后,將這些數據插入頁面中需要放這些數據處的div中


document.getElementById('btnId'+index).onclick = function() {         //動態添加事件,若在每條數據的后面要添加件事傳參,此方式可傳一個對象過去
addNumberBySearch(element);                        //調用這個方法,把對象傳過去,

}

 

//或者是在頁面中定義方法,此處傳不同參數,同樣使用replace方法

 

});

}
});

 

function addNumberBySearch(element){
//在此方法中添加操作
element.userid          //獲取屬性值
}

      拼接字符串的時候,遇到傳值的問題,可選擇方法傳值(可以在button里面onclick=aa(參數1,參數2))

 

 

 

 

 

 

 

 

   

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM