天天看點

Javascript版的Repeater控件實作

其實有點标題黨了,呵呵,主要是項目的特殊性,出于性能考慮項目經理規定不能用任何服務端控件(包括Repeater控件),同時盡量減少服務端處理,并盡可能壓縮最終生成的html源代碼,是以隻用JS實作。

代碼:

<html>

<head>

    <title>JavaScript的Repeater控件實作--made by 菩提樹下的楊過</title>

    <script type="text/javascript">

        /*

        hashTable的javascript實作

        */

        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() {

                    delete this.__hash[k];

        }

        //替換字元串函數(strReplace中如果有正規表達式的特殊字元串,可能會出錯)

        function replace(strSource, strReplace, strDestination) {

            var reg = new RegExp(strReplace, "g");

            return strSource.replace(reg, strDestination);

        /*測試replace函數

        var s = "a1{0}2{0}3";

        s = replace(s,"\\{0\\}","***");

        alert(s);

        */    

    </script>

</head>

<body>

    <div id="Repleater1">

    </div>

      //模闆替換開始

        var _sData = "1,2,3|a,b,c|x,y,z"; //實際資料字元串(服務端輸出)

        var _arrData = _sData.split("|"); //資料數組

        var _template = "<div>{1}--{2}--{3}--{2}</div>"; //資料行模闆

        var _fields = ['1', '2', '3']; //模闆中包含的辨別數組

        var _html = "";

        for (var i = 0; i < _arrData.length; i++) {

            var _htmlRows = _template; //初始行預設為行模闆

            var _arrTemp = _arrData[i].split(",");

            var _hash = new hashTable();

            //将模闆辨別與實際資料,變成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]))//根據模闆辨別替換為實際資料

            }

            _html += _htmlRows;

        document.getElementById("Repleater1").innerHTML = _html;

</body>

</html>

歡迎轉載 ,但請注明來自菩提樹下的楊過​

作者:菩提樹下的楊過

本文版權歸作者所有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接配接,否則保留追究法律責任的權利。

繼續閱讀