优化嵌套循环以使用jQuery创建HTML元素

时间:2013-04-25 07:57:53

标签: javascript jquery loops optimization

我正在使用HTML / Javascript开发屏幕键盘。键盘是在运行时生成的。

我正在使用JSON数据结构来存储不同的键盘布局,语言设置等。

var initParams = {
    keyboardLanguage: "de",
    keyboardLayout: {
        de: {
            row1: ["Q","W","E","R","T","Z","U","I","O","P"],
            row2: ["A","S","D","F","G","H","J","K","L"],
            row3: ["Y","X","C","V","B","N","M"]
        },
        en: {
            row1: ["Q","W","E","R","T","Y","U","I","O","P"],
            row2: ["A","S","D","F","G","H","J","K","L"],
            row3: ["Z","X","C","V","B","N","M"]
        }       
    }
}

这是完成工作的功能:

function CreateKeyHtmlElements(){

    var divElement = document.createElement("div");

    for(var obj in initParams.keyboardLayout[initParams.keyboardLanguage]){

        var keyRow = divElement.cloneNode(false);
        keyRow.id = "key" + obj;
        keyRow.className = "keyboard-key-row";

        for(var i = 0, l = initParams.keyboardLayout[initParams.keyboardLanguage][obj].length; i < l; i +=1){

            var key = divElement.cloneNode(false);
            key.id = "key-" + initParams.keyboardLayout[initParams.keyboardLanguage][obj][i];
            key.className = "keyboard-key";

            key.textContent = initParams.keyboardLayout[initParams.keyboardLanguage][obj][i];

            keyRow.appendChild(key);

            $(key).appendTo(keyRow);

        }

        $(keyRow).appendTo($("#keyboard-key-box"));

    }

}

是否有任何有效的方法可以使用jQuery优化此功能,尤其是循环。

提前致谢。

1 个答案:

答案 0 :(得分:0)

实际上有一个特殊的HTML元素用于聚合html,而不是用于实际的dom操作

var fragment = document.createDocumentFragment(); 

但是只要基准测试没有显示片段方法和通过innerHTML插入sting之间的实际差异(proof) 你可以这样做:

var result = '<div class="keyboard">';    
$(initParams.keyboardLayout[initParams.keyboardLanguage]).each(function(i,obj){
       result += '<div class="row">';
       result += '<div class="key">'+obj.join('</div class="key"><div>')+'</div>';
       result += '</div>';
    })
$(".target").append(result);

这不会让你有机会添加ID,但实际上并不重要,只是在绑定时使用$(el).index()获取列索引并$(el).parent().index()获取行