双击可拖动项目

时间:2014-03-17 19:30:21

标签: jquery jquery-ui

我有一个黄色按钮,可以在灰色面板上拖放。我用" handleDragStop"用于处理用户拖放黄色按钮时需要完成的所有任务的功能。一切都很好。但是,我想知道如何启用用户双击黄色按钮并具有与拖放时相同的行为?

$(".top-icon").draggable({
        connectToSortable: '#content',
        helper: myHelper,
        stop: handleDragStop
});

function handleDragStop(event, ui) {
        var current_text = '<div class="color-box"><b>Yellow Box ' + i + '</b>' + '<div class="yellow-content">' + '<div class="item">Item 1</div>' + '<div class="item">Item 2</div>' + '<div class="item">Item 3</div>' + '<div class="add-item">Add New Item</div>' + '</div>' + '</div>';
        $('#content .top-icon').after(current_text);

        i++;

        var $new_insert_item = $('#content .top-icon').next();
        $('#content .top-icon').remove(); // remove the clone .top-icon inside #content

        console.log('hi');
        // when click on Add New Item button
}
// end of handleDragStop

我可以在调用draggable之后应用dblclick事件,如下所示:

$(".top-icon").draggable({
        connectToSortable: '#content',
        helper: myHelper,
        stop: handleDragStop
})
.dblclick(function() {

    alert('hi');
    // Do the same tasks as handleDragStop....

});

但是,我想知道是否有一种方法可以为draragable和dblclick共享handleDragStop的功能,这样我就不需要为draggable维护一个函数handleDragStop,而为dblcclick设置另一个类似handleDragStop的函数?谢谢你的帮助。

以下是jsfiddle

1 个答案:

答案 0 :(得分:1)

你的handleDragStop()函数在两个事件处理程序中都可以正常工作。其中唯一可拖动的代码是$('#content .top-icon').after(current_text);和CMIIW,但我不明白为什么你也不能做$('#content').append(current_text);,这在两种情况下都有效。试试这个:http://jsfiddle.net/tonicboy/Tt7Fb/

JS:

$(function () {

    $('#content').sortable({
        placeholder: 'ui-state-highlight'
    });


    $(".top-icon").draggable({
        connectToSortable: '#content',
        helper: myHelper,
        stop: handleDragStop
    }).dblclick(function(e) {

    handleDragStop(e);

});;


    function myHelper(event) {
        return $(this).clone();
    }

    var i = 1;

    function handleDragStop(event, ui) {
        debugger;

        var current_text = '<div class="color-box"><b>Yellow Box ' + i + '</b>' + '<div class="yellow-content">' + '<div class="item">Item 1</div>' + '<div class="item">Item 2</div>' + '<div class="item">Item 3</div>' + '<div class="add-item">Add New Item</div>' + '</div>' + '</div>';
        $('#content').append(current_text);

        i++;

        var $new_insert_item = $('#content .top-icon').next();
        $('#content .top-icon').remove(); // remove the clone .top-icon inside #content

        console.log('hi');
        // when click on Add New Item button



    }
    // end of handleDragStop


    $('#content').on('click', '.add-item', function () {

        var $this = $(this);
        var item_count = $this.siblings('.item').length + 1;
        console.log(item_count);

        var str_item = '';
        str_item = '<div class="item">Item ' + item_count + '</div>';

        $(str_item).insertBefore($this);


    });
});
相关问题