我是javascript的新手。我想制作的按钮应该每次都添加一个新卡片到我的网页。不幸的是我的代码不起作用。你能帮助我吗?
我的代码: HTML:
<div class="plus">+</div>
<button onclick="newPerson()" class="plus">
<div class="item">
<p>title</p>
</div>
</button>
<div class="item">
<p>Title</p>
</div>
<div class="item">
<p>Title</p>
</div>
<div class="item">
<p>Title</p>
</div>
<div class="item">
<p>Title</p>
</div>
<div class="item">
<p>Title</p>
</div>
<div class="item">
<p>Title</p>
</div>
<div class="item">
<p>Title</p>
</div>
javaScript代码:
function newPerson() {
document.getElementByClassName("item")
};
答案 0 :(得分:1)
这样做
<div id = "main">
//your same html code
</div>
<script>
function newPerson() {
var newdiv = document.createElement('div');
newdiv.className+='item';
var newp = document.createElement('p');
newp.innerHTML = "TItle";
newdiv.appendChild(newp);
document.getElementById('main').appendChild(newdiv);
}
</script>
您需要通过JS创建元素并将其附加到文档
答案 1 :(得分:1)
这是另一种解决方法:
function newPerson() {
$('#wrapper').append('<div class="item"><p>Title</p></div>')
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
<div class="plus">+</div>
<button onclick="newPerson()" class="plus">
<div class="item">
<p>title</p>
</div>
</button>
<div class="item">
<p>Title</p>
</div>
<div class="item">
<p>Title</p>
</div>
<div class="item">
<p>Title</p>
</div>
<div class="item">
<p>Title</p>
</div>
<div class="item">
<p>Title</p>
</div>
<div class="item">
<p>Title</p>
</div>
<div class="item">
<p>Title</p>
</div>
</div>
&#13;
答案 2 :(得分:1)
试一试:
$(document).ready(function(){
$("button.plus").on("click",function(){
$("div:last").after("<div class=item><p>Title</p></div>");
})
})
这是演示:UpdatedDemo