添加动态按钮到开头

时间:2015-07-07 11:47:06

标签: javascript jquery

我在DIV中添加了几个按钮。

var newVr = "";
for(i=0; i<5; i++){
  newVr += '<button type="button" class="abc">New</button>';
}
document.getElementById('extraDIV')innerHTML += newVr;

如何将按钮添加到按钮的末尾,如何在开头添加新按钮?

添加新按钮后的预期输出,例如

[new] [new] [old] [old] [old] [old] [old] [old]

5 个答案:

答案 0 :(得分:1)

您可以使用prepend()

for(i=0; i<5; i++){
  $('#extreDIV').prepend('<button type="button" class="abc">New</button>');
}

for (i = 0; i < 5; i++) {
  $('#extreDIV').prepend('<button type="button" class="abc">New</button>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="extreDIV">
  <button type="button" class="abc">Old</button>
  <button type="button" class="abc">Old</button>
  <button type="button" class="abc">Old</button>
</div>

答案 1 :(得分:1)

因为您已使用jquery标记了问题

for (i = 0; i < 5; i++) {
    $("#extraDIV").prepend('<button type="button" class="abc">New</button>');
}

答案 2 :(得分:1)

尝试使用prepend()之类的,

var newVr = "";
for(i=0; i<5; i++){
     newVr += '<button type="button" class="abc">New</button>';
}
$('#extreDIV').prepend(newVr);

var newVr = "";
for(i=0; i<5; i++){
     newVr += '<button type="button" class="abc">New '+(i+1)+'</button>';
}
$('#extreDIV').prepend(newVr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="extreDIV"></div>

答案 3 :(得分:0)

您可以使用Node.insertBefore()

&#13;
&#13;
// Create a new, plain <span> element
var sp1 = document.createElement("span");
sp1.innerHTML = 'I am new span ';

// Get a reference to the element, before we want to insert the element
var sp2 = document.getElementById("childElement");

// Get a reference to the parent element
var parentDiv = sp2.parentNode;

// Insert the new element into the DOM before sp2
parentDiv.insertBefore(sp1, sp2);
&#13;
<div id="parentElement">
  <span id="childElement">foo bar</span>
</div>
&#13;
&#13;
&#13;

答案 4 :(得分:0)

在jsFiddld https://jsfiddle.net/92j135v9/1/prepend中找到示例。

另请查看jQuery文档中的prep和http://api.jquery.com/prepend/以获取更多示例。