2017-03-20 3 views
0

기본적으로 출판물 목록에 입력 된 숫자를 변경하려고합니다. 문제는 내가 입력을 변경할 때마다 이전 발행물과 발행물 수량을 유지한다는 것입니다. 예를 들어 :발행물을 복제하지 않고 목록에 추가

내가 처음 입력 2 배에 클릭하고이 내가받을 것입니다 :

게시 1 : 수량 : 1 개
게시를 1 : 수량 : 어떻게해야합니까 2

당신은 클릭 할 때 입력에서 이전 수량을 대체합니다. 그래서 예를 들면 :

출판 일 : 수량 : 1 개
출판 일 : 수량 2
게시 2 : 수량 1 개

공지 사항 취소 선. 더 이상 존재하지 않아야합니다. 수량이 업데이트되었습니다. CODEPEN

http://codepen.io/Jesders88/pen/evVrrw

HTML

<input type="number" data-name="something here" data-qty="1" data-id="1"> 
<input type="number" data-name="something else" data-qty="3" data-id="2"> 
<input type="number" data-name="something other" data-qty="5" data-id="3"> 

JAVASCRIPT

publications = new Array; 

$('input').on('change', function(e){ 
    e.preventDefault(); 

    var pid = parseInt($(this).data('id')); // id of thing 
    var name = $(this).data('name'); // name of thing 
    var qty = parseInt($(this).data('qty')); 

    console.log(pid); 
    console.log(name); 
    console.log(qty); 

    if(typeof publications[pid] == 'undefined') 
    { 
    publications[pid] = new Array; 
    publications[pid][0] = name; 
    publications[pid][1] = qty; 
    } 
    else 
    { 
    publications[pid][1] = qty; 
    } 

    console.log(publications); 

    $.each(publications, function(i, l){ 
    //console.log("Index #" + i + ": " + l); 
    console.log(l[0]+' has a qty of: '+l[1]); 
    }); 

}); 

답변

1

aa는 몇 가지 문제가 가장 중요하게 여기에 있습니다 : 당신이 $(this).data('qty') 업데이트되지 않으며, 따라서 항상 같은 값 . 개인적으로 배열 대신 객체를 사용하는 것이 단지 입력에 표시되는 실제 값과 분리되고 데이터 속성 대신에 동작 qty.value :

// use an object 
var publications = {}; 

$('input').on('change', function(e){ 
    e.preventDefault(); 

    var pid = parseInt($(this).data('id'), 10); // id of thing 
    var name = $(this).data('name'); // name of thing 
    var qty = parseInt($(this).val(), 10); 

    // if you must, set the new quantity into the data property 
    $(this).data('qty', qty); 

    console.log(pid); 
    console.log(name); 
    console.log(qty); 

    if(!publications[pid]) 
    { 
    publications[pid] = { 
     name: name, 
     qty: qty 
    }; 
    } 
    else 
    { 
    publications[pid].qty = qty; 
    } 

    console.log(publications); 

    $.each(publications, function(i, l){ 
    //console.log("Index #" + i + ": " + l); 
    console.log(l.name+' has a qty of: '+l.qty); 
    }); 

}); 
+0

편집. 아주 간단합니다. 나는 내가 그것을 놓쳤다라고 생각할 수 없다. :). 도와 줘서 고마워. – jesders88

관련 문제