编写用于dom操纵的代码的最佳实践是什么?

时间:2018-07-18 10:23:01

标签: javascript html dom-manipulation

因此,我正在创建一个Web应用程序,该程序将获取食谱信息,并根据食品食谱API将其打印到DOM。我正在获取JSON信息并大量操作dom。令我惊讶的是,这段代码非常不可读。这是一个片段:

//create ingredient title

const ingredientTitle = document.createElement("p");

const ingredientTitleTextNode = document.createTextNode("Ingredients");

ingredientTitle.appendChild(ingredientTitleTextNode);

const ingredientTitleParent = document.querySelector(".recipe-ingredients-item");

ingredientTitleParent.appendChild(ingredientTitle);

//create ingredient title end



//create ingredient UL and LIs

const ingredients = selectedItemJson.hits[0].recipe.ingredientLines;


const ingredientUl = document.createElement("ul");

for (let j = 0; j < ingredients.length; j++) {

  const ingredientLi = document.createElement("li");

  const ingredientTextNode = document.createTextNode(ingredients[j]);

  ingredientLi.appendChild(ingredientTextNode);

  ingredientUl.appendChild(ingredientLi);

}

const ingredientParent = document.querySelector(".recipe-ingredients-item");

ingredientParent.appendChild(ingredientUl);

//create ingredient UL and LIs end

将会有更多这样的事情。那么这是不好的做法吗?如果可以,我该怎么办。预先感谢。

1 个答案:

答案 0 :(得分:0)

1)使用innerHTML的简单示例:

var html = "";
var list = [
    {
        name: "name",
        components: [
            {name: "ingredient1", quantity: "q1"},
            {name: "ingredient2", quantity: "q2"}
        ]
    },
    {
        name: "name2",
        components: [
            {name: "ingredient3", quantity: "q1"},
            {name: "ingredient4", quantity: "q2"}
        ]
    },

]

for (var x = 0; x < list.length; x++){
    var item = list[x];
    html += "<h1>" + item.name + "</h1>";
    html +="<ul>";
    for (var y = 0; y < item.components.length; y++){
        var component = item.components[y];
        html += "<li>" + component.name + ", quantity: " + component.quantity + "</li>";
    }
    html += "</ul>";
}
var dom = document.createElement("p");
dom.innerHTML = html;
document.getElementsByTagName("body")[0].appendChild(dom);

2)使用直接dom

var body = document.getElementsByTagName("body")[0];
var p = document.createElement("p");
body.appendChild(p);

for (var x = 0; x < list.length; x++){
    var item = list[x];
    var h1 = document.createElement("h1");
    h1.innerText = item.name;
    p.appendChild(h1);
    var ul = document.createElement("ul");
    for (var y = 0; y < item.components.length; y++){
        var li = document.createElement("li");
        var component = item.components[y];
        li.innerText = component.name + ", quantity: " + component.quantity;
        ul.appendChild(li);
    }
    p.appendChild(ul);
}

JSPerf测试InnerHTML与直接dom

enter image description here

https://jsperf.com/innerhtml-vs-dom-append/1