用Java脚本硬编码,感谢一些减少此代码的建议

时间:2019-10-05 06:53:26

标签: javascript html

我尝试使用js createElement,setAttribute,appendChild来实现目标。

原始div

<div class = "form-row" id="components">
    <div class="form-group col-md-3 mb-0">
        <label for="component">Component</label>
        <input type="text" class="form-control" id="component" placeholder ="component" value="">
    </div>
    <div class="form-group col-md-3 mb-0">
        <label for="component">Each price</label>
        <input type="number" class="form-control" id="price" min=0 placeholder = "Each Price" value="">
    </div>
</div>

将元素附加到父div的功能

function components(){
    var x = document.getElementById("components");

    var div1 = document.createElement("div");
    div1.setAttribute("class","form-group col-md-3 mb-0")


    var item = document.createElement("Input");
    item.setAttribute("type","text");
    item.setAttribute("id","item");
    item.setAttribute("value","");
    item.setAttribute("class","form-control");
    item.setAttribute("placeholder","item");

    var div2 = document.createElement("div");
    div2.setAttribute("class","form-group col-md-3 mb-0")

    var price = document.createElement("Input");
    price.setAttribute("type","number");
    price.setAttribute("id","price");
    price.setAttribute("min",0);
    price.setAttribute("value","");
    price.setAttribute("class","form-control");
    price.setAttribute("placeholder","price");

    div1.appendChild(item);
    div2.appendChild(price);

    x.appendChild(div1);
    x.appendChild(div2);
}

上面的函数与onclick事件一起使用并创建子div。

1 个答案:

答案 0 :(得分:0)

为什么不只设置容器的innerHTML

function components(){
    var x = document.getElementById("components");
    x.innerHTML += `
<div class="form-group col-md-3 mb-0">
  <label for="component">Component</label>
  <input type="text" class="form-control" id="component" placeholder ="component" value="">
</div>
<div class="form-group col-md-3 mb-0">
  <label for="component">Each price</label>
  <input type="number" class="form-control" id="price" min=0 placeholder = "Each Price" value="">
</div>
    `;
}

这还不是很清楚,但是如果您打算多次调用components,请改用insertAdjacentHTML,以避免破坏容器中的现有元素(这样,使用值的输入就不会重置,以使附加到子级(如果有)的事件侦听器不会丢失):

function components(){
    var x = document.getElementById("components");
    x.insertAdjacentHTML('beforeend', `
<div class="form-group col-md-3 mb-0">
  <label for="component">Component</label>
  <input type="text" class="form-control" id="component" placeholder ="component" value="">
</div>
<div class="form-group col-md-3 mb-0">
  <label for="component">Each price</label>
  <input type="number" class="form-control" id="price" min=0 placeholder = "Each Price" value="">
</div>
    `);
}