jquery - 从 jquery 可排序中删除 div

标签 jquery jquery-ui jquery-ui-sortable

我为我的 Intranet 开发了一个“类似 Google map ”的用户界面,用户可以在其中添加步骤来计算路线和距离。我正在使用可排序的 div 来重新排序步骤。现在我想删除步骤,但我的 JavaScript/jQuery 代码根本不起作用。你能帮我吗?

我的 jQuery 代码:

$(document).ready(function() {
        $("#sortable").sortable();
        $("#sortable").disableSelection();
});



    function addStep() {
        var temp = $('.template').clone();
        $(temp).removeClass("template");
        $(temp).addClass("sort");
        $('#sortable').append(temp);

    }
    function removeStep() {

        $(this).closest('div.sort').remove();
        $("#sortable").sortable('refresh');
    }

还有我的 HTML:

//template to add new step
 <div class="template">
        <input type="text" name="addressN" value="" class="address" />
        <input type="button" class="remove" value="Remove" onclick="removeStep();" />
    </div>
//sortable list of step
    <div id="sortable">
        <div class="sort">
            <input type="text" name="Start" value="" class="address" />
        </div>
        <div class="sort">
            <input type="text" name="End" value="" class="address" />
        </div>
    </div>
    <input type="submit" value="Get Route!" onclick="showLocation(); return false;" />
    <input type="submit" value="Add Step" onclick="addStep(); return false;" />

提前致谢!

最佳答案

您的 addStep() 函数有问题。我将尝试通过在您的原始代码中添加一些注释来进行解释:

function addStep() {
 // Here, you store a reference to the jQuery Object containing the clone in the var temp.
 var temp = $('.template').clone();
 // Here, you wrap temp (which already is a jQuery Object) inside $().
 // Fix: replace '$(temp)' by 'temp'
 $(temp).removeClass('template');
 $(temp).addClass('sort');
 $('#sortable').append(temp);
}

修复此问题并加上一些额外的优化后,将变为:

function addStep() {
 $('.template').clone().removeClass('template').addClass('sort').appendTo('#sortable');
}

此外,您的 removeStep() 函数错误地使用了 this。您可能想要执行以下操作:

$.fn.removeStep = function() {
 // `this` is now a reference to the jQuery Object on which `.removeStep()` was invoked 
 this.closest('div.sort').remove();
 $('#sortable').sortable('refresh');
 // Allow chaining
 return this;
}

现在,您可以从 HTML 模板中省略 onclick="removeStep();" ,并在 jQuery 中使用类似的内容:

$('.remove').live('click', function() {
 $(this).removeStep();
}

关于jquery - 从 jquery 可排序中删除 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2041016/

相关文章:

jquery - 将 <div> 附加到 jQuery slider 句柄

java - XMLHttpRequest 错误 请求的资源上不存在 'Access-Control-Allow-Origin' header

jquery - 如何使菜单始终附加在顶部

javascript - 替换鼠标上选定的文本

c# - 将 datagridview 的最后一行设置为不可排序(总是在底部)

javascript - 可排序的容器/边界

jquery - 拖放克隆

jquery - 如何在销毁 jQuery 插件时删除事件?

jQuery 可拖放定位

javascript - 如何使 Bootstrap 日期选择器中的容器附加到特定元素?