0

我正在使用 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。

提前致谢。

4

1 回答 1

0

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

var fragment = document.createDocumentFragment(); 

但只要基准测试没有显示片段方法和通过 innerHTML (证明)插入刺痛之间的实际差异,您可以执行以下操作:

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()获取行时

于 2013-04-25T08:16:43.290 回答