其實有點標題黨了,呵呵,主要是項目的特殊性,出于性能考慮項目經(jīng)理規(guī)定不能用任何服務(wù)端控件(包括Repeater控件),同時盡量減少服務(wù)端處理,并盡可能壓縮最終生成的html源代碼,所以只用JS實現(xiàn)。
代碼:
<html>
<head>
<title>JavaScript的Repeater控件實現(xiàn)--made by 菩提樹下的楊過</title>
<script type="text/javascript">
/*
hashTable的javascript實現(xiàn)
*/
function hashTable() {
this.__hash = {};
//添加key-value鍵值對
this.add = function(key, value) {
if (typeof (key) != "undefined") {
//if it not contains in hashtable
if (!this.contains(key)) {
this.__hash[key] = typeof (value) == "undefined" ? null : value;
return true;
}
else {
return false;
}
}
};
//刪除key-value鍵值對
this.remove = function(key) {
delete this.__hash[key];
};
this.count = function() {
var i = 0;
for (var obj in this.__hash) {
i++;
}
return i;
};
//取得指定鍵值
this.items = function(key) {
return this.__hash[key];
};
//檢查是否包含指定鍵
this.contains = function(key) {
return typeof (this.__hash[key]) != "undefined";
};
//清空哈希表
this.clear = function() {
for (var obj in this.__hash) {
delete this.__hash[k];
}
};
}
//替換字符串函數(shù)(strReplace中如果有正則表達式的特殊字符串,可能會出錯)
function replace(strSource, strReplace, strDestination) {
var reg = new RegExp(strReplace, "g");
return strSource.replace(reg, strDestination);
}
/*測試replace函數(shù)
var s = "a1{0}2{0}3";
s = replace(s,"\\{0\\}","***");
alert(s);
*/
</script>
</head>
<body>
<div id="Repleater1">
</div>
<script type="text/javascript">
//模板替換開始
var _sData = "1,2,3|a,b,c|x,y,z"; //實際數(shù)據(jù)字符串(服務(wù)端輸出)
var _arrData = _sData.split("|"); //數(shù)據(jù)數(shù)組
var _template = "<div>{1}--{2}--{3}--{2}</div>"; //數(shù)據(jù)行模板
var _fields = ['1', '2', '3']; //模板中包含的標識數(shù)組
var _html = "";
for (var i = 0; i < _arrData.length; i++) {
var _htmlRows = _template; //初始行默認為行模板
var _arrTemp = _arrData[i].split(",");
var _hash = new hashTable();
//將模板標識與實際數(shù)據(jù),變成key-value鍵值對
for (var j = 0; j < _fields.length; j++) {
_hash.add(_fields[j], _arrTemp[j]);
_htmlRows = replace(_htmlRows, "\\{" + _fields[j] + "\\}", _hash.items(_fields[j]))//根據(jù)模板標識替換為實際數(shù)據(jù)
}
_html += _htmlRows;
}
document.getElementById("Repleater1").innerHTML = _html;
</script>
</body>
</html>
歡迎轉(zhuǎn)載 ,但請注明來自菩提樹下的楊過 http://www.cnblogs.com/yjmyzz/archive/2009/06/19/1506849.html
Tag標簽: javascript,repeater