2014-11-14 23 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