无法定位JSON创建的块

时间:2015-06-23 14:47:33

标签: javascript jquery json jquery-ui draggable

出于某种原因,我很难在JSON / jquery创建的元素上实现draggable(jquery或draggabilly)。

这是我的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(仅用于测试),也不能定位块变量的类(块)。有谁知道为什么? draggable可以与页面上的任何其他元素一起使用。

真诚的,塞巴斯蒂安

2 个答案:

答案 0 :(得分:0)

两件事:

  • 您要使用id="draggable"附加多个元素。 Ids应该是独一无二的。
  • 没有证据可以在附加元素上调用draggabilly

需要调用Draggabilly:

  • 页面加载时已存在的所有块
  • 附加后动态创建的块

就个人而言,我会编写类似这样的代码:

window.onload = function() {
    var draggabilly_options = {
        // options...
    };
    function create_button(key, val) {
        $('<button/>', {
            'id': val.name,
            'class': 'btn',
            'style': 'background-color:' + val.color,
            'html': val.name,
        })
        .appendTo("#field")
        .on('click', create_block.bind(val));
    }
    function create_block() {
        $('<div/>' {
            'class': 'block ' + this.name + '-piece',
            'html': this.name + '<div class="close">-</div>'
        })
        .appendTo('#boxes')
        .draggabilly(draggabilly_options) //invoke draggabilly on the div.block just added
        .data('cost', this.cost)
        .find('.close')
        .on('click', close);
    }

    function close() {
        $(this).closest(".block").remove();
        setTotal();
    }

    function setTotal() {
        var total = 0;
        $(".block").each(function() {
            total += parseInt($(this).data('cost'));
        });
        $('.totalSum').html(total);
    };

    $.getJSON( "ajax/test.json", function(data) {
        $.each(data.createButton, create_button);
        setTotal();
    });

    //You need this only if the page loads with any "draggable" blocks already in place.
    $("#boxes .block").draggabilly(draggabilly_options);
};

答案 1 :(得分:0)

感谢您的回复。我从您发布的代码中得到了一些建议,并将其写成这样;

// Start this after window is loaded
window.onload = function(){ 
// Init draggabilly
var draggabilly_options = {
    // Dragabilly options
    containment: '#boxes',
    grid: [ 100, 100 ]
};

并在按钮点击功能中进一步定义,如此;

    button.on("click", function(){
        var block = $('<div id="block-' + val.id + '" class="block ' + val.name + '-piece"></div>');
        var close = $('<div class="close">-</div>');
        $(block).append(close);
        block.data('cost', val.cost);
        block.draggabilly(draggabilly_options);

这似乎为我解决了!感谢您的帮助和解答,他们解决了我的问题:)