2016-12-24 8 views
-3

私のdivボックスのデータ属性 "data-price"の数字の合計をjavascriptで集計し、結果をdivボックスにも表示したい。何かがドロップされたときにHtml5のJavascriptでdiv-boxesの "data-price"属性を数える方法は?

私が持っている問題は、私は次のJavaスクリプトを得たこと、ですが、それが唯一の入力の値の代わりに、私のdivボックスの「データ・価格」-attributesをカウント:

<script type="text/javascript"> 
function findTotal(){ 
var arr = document.getElementsByName('qty'); 
var tot=0; 
for(var i=0;i<arr.length;i++){ 
    if(parseInt(arr[i].value)) 
     tot += parseInt(arr[i].value); 
} 
document.getElementById('total').value = tot; 
} 
</script> 

マイDIVボックス:

<div name="qty" data-price="1.12" dragable="true">Text</div> 

出力のdivボックス:

<div id="total">0</div> 

は何私は変更することがありますか?

+1

「java」は**「** javascript」と同じではありません! – Andreas

+0

「html5でデータ属性にアクセスする」方法を尋ねているようですので、[**ウェブ検索中**](https://www.google.com/search?q=access+data+ attribute + in + html5)、あなたはどのように学ぶでしょう。 – Andreas

+0

私はスクリプトがすべてのデータ属性 "データ価格"の数を合計するようにします。 – Jolp

答えて

2

あなたは次のようにします。

if (parseInt(arr[i].value)) 

デフォルトHTML 属性を持たない要素のプロパティにアクセスしようとしています。 data-* attributeであるデータ価格(値ではない)属性にアクセスするように思われます。また、浮動小数点数は整数ではなく、浮動小数点数を使用するため、使用してください。

if (parseFloat(arr[i].dataset.price)) 

window.onload = function() { 
 
    var total = 0; 
 
    var nodes = document.getElementsByName('qty'); 
 
    [].forEach.call(nodes, function(node) { 
 
    console.log(node.dataset.price); 
 
    total += parseFloat(node.dataset.price) 
 
    }) 
 
    console.log('Total: ' + total); 
 
}
<div name="qty" data-price="1.12" dragable="true">This one costs 1.12</div> 
 
<div name="qty" data-price="1.45" dragable="true">This one costs 1.45</div>

displaying values as currencyについて、ここで多くの質問と回答があります。

+0

小数点以下2桁も表示できますか? – Jolp

関連する問題