2015-01-13 2 views
0

저는 JavaScript에서 꽤 새로워졌습니다. 생성자의 버튼이 내가 만든 테이블에 나타나지 않는 이유를 꽤 잘 모르겠습니다. 내가 생성자에 버튼을 만들거나 할 수 있다면 사람이 내가 동적으로자바 생성자에서 버튼 만들기

  <!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <meta http-equiv="Content-Type" content="text/html"> 
    <title>Client Side Shopping Basket</title> 
    <meta name="author" content="Justin Butterworth"> 
    <link href="basket.css" rel="stylesheet" type="text/css" media="screen" /> 
</head> 

<body> 
<div id="container"> 
    <header id="title"> 
     <h1>Products</h1> 
    </header> 
    <div id="output"> 
     <table border="1" id="tProducts"> 
      <tr> 
       <th>Name</th> 
       <th>Description</th> 
       <th>Quantity</th> 
       <th>Price</th> 
       <th>Gender</th> 
      </tr> 
     </table> 
    </div> 
    <br /><br /> 
    <header id="title"> 
     <h1>Shopping Basket</h1> 
    </header> 
    <div id="totals"> 
     <table border="1"> 
      <tbody> 
       <!-- tax + subtotal --> 
       <tr class="netcost"> 
        <td class="light">Net Total:</td> 
        <td colspan="2" class="light"></td> 
        <td>&nbsp;</td> 
        <td>&nbsp;</td> 
       </tr> 
       <tr class="totalcost"> 
        <td class="light">Total:</td> 
        <td colspan="2">&nbsp;</td> 
        <td colspan="2"><span class="thick">£225.45</span></td> 
       </tr> 

       <!-- checkout btn --> 
       <tr class="checkoutrow"> 
        <td colspan="5" class="checkout"><button id="submitbtn">Checkout Now!</button></td> 
       </tr> 
      </tbody> 
     </table> 
    </div> 
</div> 
<p id="test"></p> 

<script> 
var productList=[]; //where product objects are to be held 
var basket=[]; 

//constructor 
function Products(name, description, quantity, price, gender) 
{ 
    var obj = this; // a reference to this object 

    this.name = name; 
    this.description = description; 
    this.quantity = quantity; 
    this.price = price.toFixed(2); 
    this.gender = gender; 

    this.getName = function() { 
     return this.name 
    }; 

    this.getPrice = function() { 
     return '\u00A3' + this.price; 
    }; 
} 

//instantiate new products 
var shorts = new Products('Shorts', 'Stone Wash Demin Shorts', 20, 25.90, 'F'); 
var bag = new Products('Bag', 'Leather Shoulder Bag', 4, 50.45, 'F'); 
var blouse = new Products('Blouse', 'Vintage Blue Silk Polka Dot Blouse', 8, 45.99, 'F'); 
var boots = new Products('Boots', 'Soft Leather Brown Ankle Boots', 3, 65.35, 'F'); 
var belts = new Products('Belts', 'Woven Finish Fashion Belt', 15, 21.99, 'F'); 
var shirt = new Products('Shirt', 'Jacquard Pattern Wrangler Western Shirt', 19, 34.87, 'M'); 
var shoes = new Products('Shoes', 'Suede Ankle Boots', 6, 55.00, 'M'); 
var trousers = new Products('Trousers', 'Izod Peach Chinos', 23, 31.75, 'M'); 
var belt = new Products('Belt', 'Suede Casual Belt', 4, 22.98, 'M'); 
var hat = new Products('Hat', 'Trilby Style Brown Woven Fix', 2, 67.80, 'M'); 

//add objects to an array 
productList.push(shorts, bag, blouse, boots, belts, shirt, shoes, trousers, belt, hat); 


//function to display full product list 
function displayProducts(tProducts) 
{ 
    var table = document.getElementById('tProducts'); // reference to the table to add rows to 
     for (var i = 0; i < tProducts.length; ++i) // iterate through the array for each of the products 
    { 
     var product = tProducts[i]; // keep a reference to each individual product 
     var row = document.createElement('tr'); // create a row element to append cells to 
     var properties = ['name', 'description', 'quantity', 'price', 'gender']; // properties of the array elements 

     for (var j = 0; j < properties.length; ++j) // append each one of them to the row in question, in order 
     { 
      var cell = document.createElement('td'); // create new data cell for names 
      cell.innerHTML = product[properties[j]]; // set name of property using bracket notation (properties[j] is a string, which can be used to access properties of product) 
      row.appendChild(cell); // add to end of the row 
     } 
     row.appendChild(createBtn()); 
     table.appendChild(row); // add new row to table 
    } 
}; 

function createBtn() { 
     var btn = document.createElement('input'); 
     btn.type = 'button' 
     btn.name = name; 
     btn.value = 'Add'; 
     btn.onclick = function() { 
      return obj.getPrice(); 
     }; 
    return btn; 
}; 

displayProducts(productList); 
</script> 

</body> 
</html> 

좋아요 버튼을 생성하기 위해 별도의 기능을 필요로 말해 줄 수 .. 나는 버튼 요소에 자신이 만든하지만 어떻게 난의 이름을 업데이트 할 수 있습니다 제품 이름 단추? 자바 스크립트에서 머리 글자를 얻으려고하는 한 가지 측면 인 범위 문제입니다.

var p = new products("name", "des", 1, 1, ""); 
p.createBtn(); 

하고 나를 위해 잘 작동 :

@RobG 또한 내가 당신의 기능을 시도 모든 코드

+1

어떻게'.createBtn()'함수가 호출되고 있습니까? 그리고'document.write()'는 아마도 잘못된 접근법 일 것입니다. – Pointy

+0

load 이벤트가 전달 된 후 * instance.createBtn *을 호출하는 경우 * document.write *는 모든 내용의 문서 전체를 지우고 단일 단추를 삽입합니다. – RobG

+1

* createBtn * 함수는 DOM 메서드를 사용하여 버튼을 만들고 새로 만든 버튼을 반환하여 문서의 올바른 위치에 추가하거나 버튼이 될 인수로 DOM 요소를 가져와야합니다 에 추가됨. 오, 그리고 생성자 안에서 이것을하는 것은 말이되지 않습니다. * this.getPrice *는 * products * 인스턴스가 아닌 버튼의 * getPrice * 속성을 참조합니다. – RobG

답변

0

몇 가지 팁 : 다른 외부 자바 스크립트 페이지에 코드를 사용

var doc = document, bod = document.body, Product; 
function E(id){ 
    return doc.getElementById(id); 
} 
function C(t){ 
    return doc.createElement(t); 
} 
(function(){ 
// add other vars, functions and so forth to remain inside scope 
Product = function(name, description, quantity, price, gender){ 
    var productContext = this; 
    this.name = name; this.description = description; this.quantity = quantity; 
    this.price = price.toFixed(2); this.gender = gender; 
    this.getPrice = function(){ 
    return this.name+' \u00A3'+this.price; 
    } 
    this.createButton = function(where){ 
    var btn = C('input'); 
    btn.type = 'button'; btn.id = this.name; // will be a problem if there's a space 
    btn.value = 'Add'; 
    btn.onclick = function(ev){ 
     var e = ev || event; // event Object to var e 
     /* put code here 
     can use var productContext to refer to Product this 
     this refers to btn in here */ 
    } 
    where.appendChild(btn); 
    } 
} 
})(); 

바람직 자본의 첫 글자와

  • 개체 생성자 (규칙)
  • 가능한 경우 객체 메소드 i n prototype (공유 메서드를 사용하여 각 객체를 더 가볍게 만듭니다)
  • innerHTML은 DOM 메소드보다 무겁습니다. 사용하는 것이 좋지만 DOM 조작을 선호하거나 적어도 일관성을 유지하고 둘 중 하나를 선택하십시오.
function Product(name, description, quantity, price, gender) { 
    this.name = name; 
    this.description = description; 
    this.quantity = quantity; 
    this.price = price; 
    this.gender = gender; 
} 
Product.prototype.getPrice = function() { 
    // dummy output, just to test 
    alert(this.name + ' ' + '£' + this.price); 
}; 
Product.prototype.createBtn = function(parent) { 
    var input = document.createElement('input'); 
    input.id = this.name; 
    input.value = 'Add'; 
    input.type = 'button'; 
    input.addEventListener ? input.addEventListener('click', this.getPrice.bind(this), false): 
     input.attachEvent('onclick',this.getPrice.bind(this)); 
    parent.appendChild(input); 
}; 
// instantiate & append to body 
var x = new Product('product-1','some descr',5,25,'male'); 
x.createBtn(document.body); 

참고 :function().bind() 구조도 후 DOM 요소에 바인딩 된 개체의 범위를 결합 정말 유용하지만 IE9 +에서 작동합니다. 레거시 브라우저를 지원하려면 RobG의 대답 (프로토 타입이 아닌 개인 변수가 & 인 객체 내부의 메소드 사용)을 참조하십시오.

0

생성자에서 수행중인 작업을하는 것이 의미가 없습니다. 인스턴스에 의해 생성 된 버튼은 인스턴스를 생성 한 객체와 전혀 관계가 없습니다. 제품 ID 등을 사용하고 데이터 저장소 (예 : 다른 개체)에 데이터를 저장하는 것이 좋습니다.

이 생성자에게 대문자로 시작하는 이름을 부여하는 대회이며, 또한 하나의 인스턴스가 그래서 그것을 단수 이름, 예를 들어 줄과 creat :

function Product(name, description, quantity, price, gender) { 

    // Keep a reference to the instance in a closure 
    var obj = this; 

    this.name = name; 
    this.description = description; 
    this.quantity = quantity; 
    this.price = price; 
    this.gender = gender; 
    this.getPrice = function() { 
    return this.name + ' ' + '£' + this.price; 
    }; 

    // Within the function, use obj to reference the instance, not this 
    this.createBtn = function() { 
    var btn = document.createElement('input'); 
    btn.type = 'button' 
    btn.name = obj.name; 
    btn.value = 'Add'; 
    btn.onclick = function() { 

     // Important to use obj here to ensure getPrice is called 
     // with expected value for this 
     // return obj.getPrice(); 

     // for testing 
     return console.log(obj.getPrice()); 
    }; 
    return btn; 
    }; 
} 

그냥 테스트가 마크 업하면 수 :

를 이제
<div id="basket"></div> 

당신은 할 수 있습니다 :

var foo = new Product('foo', 'A large Foo', 6, 2.5, 'Pan'); 
document.getElementById('basket').appendChild(foo.createBtn()); 

그러나, 버튼을 클릭하면 가격을 반환 디버그 라인을 추가했습니다.

+0

어디에서 버튼을 추가해야합니까? displayTable 함수에서 행을 만들 때? 감사합니다 – user3414871

+0

'cell.innerHTML = product [properties [j]];','cell.appendChild (foo.createBtn());'을 사용합니다. – RobG

0

이어야한다 더 같은 :

var pre = onload; 
onload = function(){ 
if(pre)pre(); // executes old onload and preserves scope 
function whatever(){ 
    // normal indentation here 
} 
var prod = new Product('SomeName', 'Description Here', 10, 12.5, 'male'); 
prod.createButton(E('someId')); 
} 
관련 문제