如何使用JS push()添加多个元素?

时间:2017-07-23 03:15:10

标签: javascript

我无法使用Javascript使用多个元素推送html数据,我希望html输出如下:

    <li class="swipeout">
      <label class="label-checkbox item-content swipeout-content">
        <input type="checkbox" name="ks-checkbox" value="Books" />
        <div class="item-media"><i class="icon icon-form-checkbox"></i></div>
        <div class="item-inner">
          <div class="item-title">Lifebuoy Soap</div>
          <div class="item-after">6.000</div>
        </div>
      </label>
      <div class="swipeout-actions-right"><a href="#" data-confirm="Are you sure want to delete this?" class="swipeout-delete">Delete</a></div>
    </li>

我试过https://jsfiddle.net/ferdyzz4/ee7c7ca9/,但输出不一样。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您不应该将div附加到您的输入中,只需将输入附加到标签上,就像以前一样:

    label.appendChild(input)

这会根据你的小提琴代码给你想要的结果:

  addAnother = function() {
      var ul = document.getElementById("list");
      var li = document.createElement("li");
      var label = document.createElement("label");
      var input = document.createElement("input");
      var div = document.createElement("div");
      var i = document.createElement("i");
      var itemInner = document.createElement("div");
      var itemTitle = document.createElement("div");
      var itemAfter = document.createElement("div");
      var swipeOut = document.createElement("div");
      var link = document.createElement("a");
      var children = ul.children.length + 1
      li.setAttribute("class", "swipeout")
       label.setAttribute("class", "label-checkbox item-content swipeout-content")
       input.setAttribute("type", "checkbox")
       input.setAttribute("name", "ks-checkbox")
       input.setAttribute("value", "Test")
      label.appendChild(input)
      div.setAttribute("class", "item-media")
      i.setAttribute("class", "icon icon-form-checkbox")
      div.appendChild(i)
      label.appendChild(div)
      li.appendChild(label)
      itemInner.setAttribute("class", "item-inner")
      itemTitle.setAttribute("class", "item-title")
      itemTitle.appendChild(document.createTextNode("Element "+children));
      itemAfter.setAttribute("class", "item-after")
      itemInner.appendChild(itemTitle)
      itemInner.appendChild(itemAfter)
      li.appendChild( itemInner )
      swipeOut.setAttribute("class", "swipeout-actions-right")
      link.setAttribute("class", "swipeout-delete");
      link.setAttribute("href", "#")
      link.setAttribute("data-confirm", "Are you sure want to delete this?" )
      swipeOut.appendChild(link);
      li.appendChild(swipeOut);

      ul.appendChild(li)
  }

小提琴:https://jsfiddle.net/L3Lqupbr/4/