<script>
var i=0;
var j="";
function app() {
j+=document.getElementById("demo").innerHTML="<button type='button'>Btn+i</button>";
}
</script>
<button type="button" onclick="app()">Add</button>
<div id="demo">
</div>
每次用户点击添加按钮时,我都会尝试在div
标记中添加按钮。
此外,我希望添加按钮显示为:Btn 1,Btn2, Btn3 ..
答案 0 :(得分:0)
#demo
内容与var i
的增量的简单串联:
var i = 0;
function app() {
document.getElementById("demo").innerHTML += "<button type='button'>Btn " +
++i + "</button>";
}
&#13;
<button type="button" onclick="app()">Add</button>
<div id="demo"></div>
&#13;
答案 1 :(得分:0)
您需要更改.innerHtml
+ = ...
并增加i
var i=0;
function app()
{
j+=document.getElementById("demo").innerHTML+="<button type='button'> Btn"+i+"</button>";
i++;
}
<button type="button" onclick="app()">Add</button>
<div id="demo">
</div>
答案 2 :(得分:0)
您需要附加HTML
var s = 0;
function app(){
s++;
var strHTML = "<button>Btn"+ s+"</button>"
document.getElementById('test').insertAdjacentHTML( 'beforeend', strHTML );
}
答案 3 :(得分:0)
或者让它更具可读性。
<script>
var i = 0;
var j = "";
function makeButton(index) {
var $button = document.createElement('BUTTON');
$button.innerHTML = 'Button ' + index;
$button.onclick = function() {
alert('You clicked button:' + index);
};
return $button;
}
function onAddButtonClick() {
document.getElementById("demo").appendChild(makeButton(i));
i++; // increase number for next time;
}
</script>
<button type="button" onclick="onAddButtonClick()">Add</button>
<div id="demo">
</div>
答案 4 :(得分:0)
var i1 = 0;
function app1()
{
var div = document.createElement('div');
div.innerHTML = "<button type='button'>Btn " + (++i1) + "</button>";
for (var child = 0; child < div.childNodes.length; child) {
document.getElementById("demo1").append(div.childNodes[child]);
}
}
var i2 = 0;
function app2() {
document.getElementById("demo2").innerHTML += "<button type='button'>Btn " +
++i2 + "</button>";
}
var d1s = new Date().getTime();
for (var j1 = 0; j1 < 1000; j1++) {
app2();
}
var d1e = new Date().getTime();
console.log((d1e - d1s) / 1000);
var d2s = new Date().getTime();
for (var j2 = 0; j2 < 1000; j2++) {
app1();
}
var d2e = new Date().getTime();
console.log((d2e - d2s) / 1000);
&#13;
<div id="demo1"></div>
<div id="demo2"></div>
&#13;
与innerHtml + =连接非常慢