2015-01-21 3 views
1
function makeUL() { 

var products = JSON.parse(localStorage["products"]); 

var list = document.createElement('ul'); 

for(var i = 0; i < products.length; i++) { 
    if(products[i].amount == 0) { 
     continue; 
    } 
    // Create the list item: 
    var item = document.createElement('li'); 

    var product = products[i]; 

    var totalPrice = product.amount * product.price; 
    var toDisplay = product.name + " " + product.amount + " @" + totalPrice + " "; 

    // Set its contents: 
    item.appendChild(document.createTextNode(toDisplay)); 
    var inputbox = document.createElement("input"); 
    inputbox.setAttribute("id", "inputboxProduct" + i); 
    inputbox.addEventListener("change", function(){ 
     changeAmountProd(inputbox.id); 
    }); 
    item.appendChild(inputbox); 

    // Add it to the list: 
    list.appendChild(item); 
} 

// Finally, return the constructed list: 
return list; 
} 

이것은 기본적으로 특정 문자열 위에 마우스를 올려 놓으면 목록을 만듭니다. 이 목록은 localstorage를 기반으로하며 해당 목록의 각 지점에 대한 입력 상자를 만듭니다. 문제는 eventlisteners를 추가하는 것입니다. 이벤트가 해당 입력 상자에서 트리거 될 때 어떤 이유로 항상 빈 값을 반환합니다.입력 요소가 값을 찾지 못함

function changeAmountProd(inputboxId) { 
var products = JSON.parse(localStorage["products"]); 

value = document.getElementById(inputboxId).value; 

if(value < 1) { 
    return; 
} 
products[i].amount = value; 

localStorage["products"] = JSON.stringify(products); 

makeUL(); 
} 
+0

를 참조하십시오, 그것은 디버그 훨씬 쉬울 것이다. – Sid

답변

2

문제는 change 이벤트의 콜백입니다. 변수 inputbox (closure을 통해 사용 가능)을 사용하여 변경된 요소를 참조하고 있지만 콜백이 호출 될 때까지 inputbox은 항상 마지막으로 생성 된 요소를 가리 킵니다.

대신보십시오 : 당신은 이것에 대한 JSFiddle을 제공 할 수있는 경우

inputbox.addEventListener("change", function(){ 
    changeAmountProd(this.id); 
}); 

addEventListener

2

이 시도 :

function makeUL() { 

    var products = JSON.parse(localStorage["products"]); 

    var list = document.createElement('ul'); 

    for(var i = 0; i < products.length; i++) { 
     if(products[i].amount == 0) { 
      continue; 
     } 
     // Create the list item: 
     var item = document.createElement('li'); 

     var product = products[i]; 

     var totalPrice = product.amount * product.price; 
     var toDisplay = product.name + " " + product.amount + " @" + totalPrice + " "; 

     // Set its contents: 
     item.appendChild(document.createTextNode(toDisplay)); 
     var inputbox = document.createElement("input"); 
     inputbox.setAttribute("id", "inputboxProduct" + i); 
     inputbox.addEventListener("change", function(){ 
      changeAmountProd(this.id); 
     }); 
     item.appendChild(inputbox); 

     // Add it to the list: 
     list.appendChild(item); 
    } 

// Finally, return the constructed list: 
    return list; 
} 
+0

네, 제 실수를 봅니다. 고마워요! 내가 대답을 수락 할 수있을 때 용납해라. – Milan

+0

@ haim770 대답을 받아 들여야한다. 그는 설명을 썼다. 나는 코드 스 니펫을 빨리 게시했다. :) –