2017-11-28 12 views
0

私はクラス.cardの中に入るいくつかのコードと、このカードを複製するjavascript関数を作成しました。 カードの内部には、簡単な計算を実行する別の機能があります。最初のカードが完全に動作するのでカードをクローンするときに問題が発生しますが、他のカードは計算をまったく行いません。 私が気づいたもう一つの問題は、最初のカードのフィールドの値が...うまくいけば、値も複製されますが、かなり空のフィールドに新しいカードを作ることになります。クローンで動作するDOM構造とjavaScript計算をクローンする方法は?

<div id="card" class="card"> 
<!-- And here comes all the card contets --> 
</div> 

<!-- And here is suposed to hold the new content with no filled fiels but with calcutations woking --> 
<div id="clone"></div> 


    //this is supposed to clone the fist card 
    function add_card(){ 
    var theCard = document.getElementById('card'); //takes the HTML id leftSide to the theLeftSide var 
    var cardClone = theCard.cloneNode(true);//cloning (float) 
    clone.appendChild(cardClone);//cloning (paste) 
} 


//And this should be doing some simple calcs 
    function calc_item(){ 
    var val_preco = document.getElementById('preco').value; 
    var val_peso = document.getElementById('peso').value; 

    var relacao_preco = val_preco/val_peso; 
    document.getElementById('preco_grama').innerHTML = (relacao_preco); 
    } 

だから私は間違っていますか?

+0

完全な事はhttp://www.comprebarato.ml/app/でありますindex.html – samu101108

答えて

1

最初の問題は、彼らはあなたがページ内の最初のマッチを取得するためにdocument.querySelector(cssSelector)を使用することができます定義

によって一意である...あなたがページでIDを繰り返すことはできませんです。この場合、セレクタとしてクラス「カード」を使用することができます

私は最初のクローンを保存しました。それから、新しいものが必要なたびにそれを複製する。次に、必要に応じてクローンの内容を変更することができます。

計算には、反復処理する要素のコレクションを取得するためにdocument.querySelectorAll()を使用します。それが働いて表示するようにCALCSは、私はすべてのカードですべての数字を足しているかわからない

var cardCount = 1 
 

 
// store a clone right away 
 
var storedClone = document.querySelector('.card').cloneNode(true); 
 

 
function add_card() { 
 
    //clone the original clone 
 
    var cardClone = storedClone.cloneNode(true); //cloning (float) 
 
    //update content of clone 
 
    cardClone.textContent = 'Card ' + (++cardCount); 
 
    clone.appendChild(cardClone); //cloning (paste) 
 
} 
 

 

 
function calc_item() { 
 
    var total = 0; 
 
    var cards = document.querySelectorAll('.card'); 
 
    cards.forEach(function(el) { 
 
    total += +/\d+/.exec(el.textContent); 
 
    }); 
 
    document.getElementById('total').innerHTML = 'Card total = ' + total; 
 
}
#clone { 
 
    border: 2px solid #ccc 
 
}
<button onclick="add_card()">Add card</button> <button onclick="calc_item()">Calc</button> 
 

 
<div id="total">Card total = 1</div> 
 

 

 

 
<!-- And here is suposed to hold the new content with no filled fiels but with calcutations woking --> 
 
<div id="clone"> 
 
<div class="card"> 
 
    Card 1 
 
</div> 
 
</div>

関連する問題