2014-11-14 19 views
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> 

感谢提前的帮助。

+0

所以,你只是想添加按钮到'ItemDiv'? – 2014-11-14 19:53:29

+0

你能分享你的标记吗?控制台中有任何错误? – 2014-11-14 19:56:35

+0

我刚才实现了它的工作。它只显示一个按钮。并且该按钮属于由构造函数构造的最后一个对象。但是如果我做了appendChild,它会显示所有与构建的对象相关的按钮。对于我上面的评论道歉我在代码中犯了一个错误,这就是为什么屏幕变为空白。我道歉。 – Skywalker 2014-11-14 20:01:29

回答

0

这会追加数据下方的按钮。您正在覆盖ItemDiv的html而不是追加。

// display the object data  
ansNode = document.createTextNode(ans); 
ItemDiv.appendChild(ansNode); 

// append the button to the data div 
ItemDiv.appendChild(this.btn); 
+0

完美!感谢您抽出时间回复。这真的帮助了我。再次感谢。 – Skywalker 2014-11-14 20:17:04