出於某種原因,我很難在JSON/jQuery創建的元素上實現可拖動(jQuery或可拖動)。無法定位JSON創建的塊
這是我的jQuery以及JSON。
var setTotal = function(){
var total = 0;
$('.block').each(function(){
total = total+parseInt($(this).data('cost'));
});
$('.totalSum').html(total);
};
window.onload = function(){
$.getJSON("ajax/test.json", function(data) {
$.each(data.createButton, function(key, val) {
var button = $('<button class="btn" id="' + val.name +'" style="background: ' + val.color + '">' + val.name + '</button>');
button.on("click", function(){
//console.log("button " + val.name + " was clicked!");
var block = $('<div id="draggable" class="block ' + val.name + '-piece">'+ val.name + '<div class="close">-</div></div>');
block.data('cost', val.cost);
block.on("click", ".close", function(){
$(this).parent().remove();
// call set total to refresh it when item is removed
setTotal();
});
$('#boxes').append(block);
// call set total to calculate total blocks' cost
setTotal();
});
$('#field').append(button);
});
});
};
這就是它在html文檔中的調用方式;
<!-- Grab Google CDN's jQuery -->
<script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script>
<!-- Grab draggable -->
<script src="//cdnjs.cloudflare.com/ajax/libs/draggabilly/1.2.0/draggabilly.pkgd.min.js"></script>
<!-- My own scripts -->
<script src="js/main.js" type="text/javascript"></script>
<script>
var $draggable = $('#draggable').draggabilly({
// options...
});
</script>
<!-- End scripts -->
現在由於某種原因,我無法定位塊變量的ID(僅測試),也不是類(塊)。有誰知道爲什麼?可拖動的頁面上的任何其他元素都可以正常工作。
真誠,塞巴斯蒂安
您是否嘗試在將塊元素附加到DOM之後調用draggabilly方法? –
不,我沒試過,會試試! –