如何获取拖动DIV框的数据集属性



我想通过JavaScript获得两个Draged Div box的Decimalnumbers来获取数据集属性"数据价格",以将它们总结。

在这里我的DIV框:

    <div name="qty" id="black" data-price="21.1" draggable="true" ondragstart="drag(event)">

我尝试使用此脚本

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

,但它仅计算非拖动盒的数据贡献。

      <script>
    function allowDrop(ev) {
        ev.preventDefault();
    }
    function drag(ev) {
        ev.dataTransfer.setData("text", ev.target.id);
    }
    function drop(ev) {
       ev.preventDefault();
        var data = ev.dataTransfer.getData("text");
        ev.target.appendChild(document.getElementById(data));
    }
      </script>

我在这里做错了什么?

您应该为我们添加整个HTML代码,以查看如何使用表单/名称/属性设置元素。我根据您的代码编写了一个简单的示例,它对我来说很好,并且仅计算掉落到target元素的元素。同样对于十进制数字,请使用parseFloat而不是parseInt

function findTotal(){
    var arr = document.querySelectorAll(".target > div");
    var tot=0;
    for(var i=0;i<arr.length;i++){
        if(parseInt(arr[i].dataset.price))
            tot += parseFloat(arr[i].dataset.price);
    }
    document.getElementById('total').textContent = tot;
}
function allowDrop(ev) {
    ev.preventDefault();
}
function drag(ev) {
    ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text");
    ev.target.appendChild(document.getElementById(data));
    
    findTotal();
}
document.getElementById('reset').onclick = function() { window.location.reload(); }
#black {
background-color: black;
color:white;
}
#red {
background-color: red;
}
#yellow {
background-color: yellow;
}
#green {
background-color: green;
color:white;
}
.qty {
width:50px;
height:50px;
display: inline-block;
margin-right:5px;
margin-bottom:5px;
}
.target {
height:100px;
border:1px solid grey;
}
<button id="reset">Reset</button>
<hr>
<form>
<div class="qty" id="black" data-price="21.1" draggable="true" ondragstart="drag(event)">21.1</div>
<div class="qty" id="red" data-price="16.5" draggable="true" ondragstart="drag(event)">16.5</div>
<div class="qty" id="yellow" data-price="7.8" draggable="true" ondragstart="drag(event)">7.8</div>
<div class="qty" id="green" data-price="3.5" draggable="true" ondragstart="drag(event)">3.5</div>
<h3>Drop items here</h3>
<div class="target" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<h3>Total: </h3>
<div id="total"></div>
</form>

我的示例也可以在这里找到:http://zikro.gr/dbg/html/jsdd/

最新更新