0
我在JavaScript中有一个构造函数,它构造了新的图书项目。那个构造函数有一个原型方法。该方法为构造函数创建的每个对象附加一个按钮。 现在我想要显示让我的第一个对象信息,然后显示它下面的相关按钮,但我似乎无法做到这一点。我只能通过使用“appendChild”标签来显示按钮。请参见下面的代码:显示javascript按钮以及它所属的对象
// the prototype to create and attach the button to the "item" object
Item.prototype.createBtn = function(item)
{
// where I display the object data. for example title, price.
var ItemDiv = document.getElementById('itemsList');
// where I display my buttons
var bask = document.getElementById('buttonsList');
// I create a new button. this.btn belongs to my constructor
this.btn = document.createElement("button");
this.btn.setAttribute("style", "width: 200px; height: 45px; background-color:#27ae60; margin-right: 500px; padding: 20px;");
// attach an event listener to my button
this.btn.addEventListener("click", function(){myBasket(item);});
// display the object data to the page
ans += '<div>' +"Title: "+ this.title + '</div>';
ans += '<div>' +"Description: "+ this.description + '</div>';
ans += '<div>' +"Price: "+ this.price +'</li><br>';
ans += "<br>";
// display the buttons into the "bask div"
bask.appendChild(this.btn);
// display the object data
ItemDiv.innerHTML = ans;
};
function myBasket(item)
{
//do something
}
取而代之的按钮被显示成不同的div我希望按钮显示。B正下方的对象数据,例如:
title: book1
price: book1
description: book1
button here
我的HTML:
<script src="basket.js"></script>
<script src="item.js"></script>
<link rel="stylesheet" href="basket.css">
<h1>The Item List</h1>
<div id="ItemDiv" class="divOne">
<div id="itemsList" class="divTwo">
<div id="test"></div>
</div>
<div id="buttonsList" class="divThree"></div>
</div>
<div id="BasketDiv">
</div>
感谢提前的帮助。
所以,你只是想添加按钮到'ItemDiv'? – 2014-11-14 19:53:29
你能分享你的标记吗?控制台中有任何错误? – 2014-11-14 19:56:35
我刚才实现了它的工作。它只显示一个按钮。并且该按钮属于由构造函数构造的最后一个对象。但是如果我做了appendChild,它会显示所有与构建的对象相关的按钮。对于我上面的评论道歉我在代码中犯了一个错误,这就是为什么屏幕变为空白。我道歉。 – Skywalker 2014-11-14 20:01:29