简体   繁体   English

无法定位JSON创建的块

[英]Can't target JSON-created block

For some reason I'm having a hard time implementing draggable (either jquery's or draggabilly) on JSON/jquery-created elements. 由于某种原因,我很难在JSON / jquery创建的元素上实现可拖动(jQuery或Draggabilly)。

This is my jQuery along with the 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);
        });
    });
};

and this is how it's called in the html document; 这就是它在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 -->

Now for some reason I can't target the ID (for testing only) nor the class (block) of the block variable. 现在由于某种原因,我既无法定位ID(仅用于测试),也无法定位block变量的类(block)。 Does anyone know why? 有人知道为什么吗? The draggable works fine with any other element on the page. 该可拖动对象可以与页面上的任何其他元素正常工作。

Sincerely, Sebastian 真诚的,塞巴斯蒂安

Two things : 两件事情 :

  • you are appending multiple elements with id="draggable" . 您要附加多个具有id="draggable"元素。 Ids should be unique. ID应该是唯一的。
  • there's no evidence of invoking draggabilly on the appended elements. 没有证据表明draggabilly对附加元素进行draggabilly

Draggabilly needs to be invoked on : Draggabilly需要在上调用:

  • any blocks that already exist on page load 页面加载时已经存在的任何块
  • dynamically created blocks after they have been appended 追加后动态创建的块

Personally, I would write the code something like this : 就个人而言,我将编写如下代码:

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);
};

Thank you for all responses. 感谢您的所有回复。 I took some advice from your code you published and put it like this; 我从您发布的代码中获取了一些建议,并像这样说。

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

and also defined it further down in the button click function like so; 并在按钮点击功能中进一步定义如下:

    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);

This appeared to solve it for me! 这似乎为我解决了! Thank you for the help and answers, they solved my problem :) 谢谢您的帮助和解答,他们解决了我的问题:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM