如何在jquery中减少这些行?

时间:2014-02-26 15:20:14

标签: jquery

我在jquery中有以下格式的许多以下行。我想减少我正在服用的行数。任何建议请!

//jquery
     $(function() { 
    $( "#draggable1" ).draggable({ revert: true, containment : '#removeme1', axis : 'x'});
    $( "#draggable2" ).draggable({ revert: true, containment : '#removeme2', axis : 'x'});  
    $( "#draggable3" ).draggable({ revert: true, containment : '#removeme3', axis : 'x' });     
    $( "#draggable4" ).draggable({ revert: true, containment : '#removeme4', axis : 'x' });     
    $( "#draggable5" ).draggable({ revert: true, containment : '#removeme5', axis : 'x' }); 
    $( "#draggable6" ).draggable({ revert: true, containment : '#removeme6', axis : 'x' });     
    $( "#draggable7" ).draggable({ revert: true, containment : '#removeme7', axis : 'x' });

                       });

4 个答案:

答案 0 :(得分:3)

只需添加一个类draggable,并根据标记设置为包含父项或将包含元素作为属性存储在可拖动元素上。

$( ".draggable" ).draggable({ revert: true, containment : 'parent', axis : 'x'});

如果容器不是父容器:

$( ".draggable" ).each(function(){
    $(this).draggable({ revert: true,
                     containment : $(this).data("container"),
                     axis : 'x'
                   });
});

// with the following HTML markup:

<div class="draggable" data-container="#removeme1"></div>

答案 1 :(得分:1)

一个简单的for循环?

$(function () {
    for (var i = 1; i <= 7; i++) {
        $("#draggable" + i).draggable({
            revert: true,
            containment: '#removeme' + i,
            axis: 'x'
        });
    }
});

答案 2 :(得分:1)

这是一个灵活的解决方案,可以解决任意数量的可拖动问题。

$(function () {
    $("div[id^='draggable']").each(function (index) {
        $(this).draggable({
            revert: true,
            containment: $(this).attr('id').val().replace('draggable', 'removeme'),
            axis: 'x'
        });
    });    
});

答案 3 :(得分:0)

$(function () {
    var someArr = [1, 2, 3, 4, 5, 6, 7];

    $.each(someArr, function (i, val) {
        $("#draggable" + val).draggable({
            revert: true,
            containment: '#removeme' + val,
            axis: 'x'
        });
    });

});