You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery动态添加的<li>无法拖拽,初始占位项正常,求解决方案

问题原因&解决办法

嘿,我知道你遇到的问题了!这是因为jQuery UI的draggable只会给页面加载时已经存在的元素绑定拖拽功能,你后来通过点击按钮动态添加的<li>根本没被加上这个拖拽行为,所以只有初始的占位列表项能正常拖拽。

解决思路

每次动态添加新的<li>元素后,都要给这个新元素单独绑定draggable方法——这种方式更高效,不会重复绑定已有元素。

修改后的代码示例

JavaScript部分(关键修改点已标记)

/* JS code for sports.html */
$(function () {
    // initialization code when DOM is ready
    //hides the second step
    $('#step2').hide();
    //tooltips
    $('#addSport').tooltip();
    //array of the auto completed sports
    var tags = ["archery", "badminton", "baseball", "softball", "football", "soccer", "volleyball", "basketball", "golf", "hockey", "swimming", "running", "track and field", "gymnastics", "dance", "rowing", "tennis", "wrestling", "weightlifting", "karate", "lacrosse", "cricket", "polo", "skating", "shooting", "handball", "fencing", "cycling", "boxing", "cheerleading", "surfing", "snowboarding", "dodgeball", "jujutso", "sumo", "taekwondo", "paintball", "pocket billiards", "pool", "fishing", "skiing", "sailing", "luge", "bobsleigh", "racquetball"];

    $("#sportName").autocomplete({
        source: function (request, response) {
            var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(request.term), "i");
            response($.grep(tags, function (item) {
                return matcher.test(item);
            }));
        }
    });

    var sportClick = 0;
    $("#addSport").click(function () {
        sportClick++;
        var sport;
        sport = $("#sportName").val();
        //takes the first sport and replaces the holding text
        if (sportClick === 1) {
            $("#sportList").html('<li>' + sport + '</li>');
            // 关键修改:替换后给新的li绑定拖拽
            $("#sportList li").draggable({ helper: "clone" }).css("cursor", "pointer");
        }
        //any other sports will be added to the first
        else {
            // 关键修改:先创建新li元素,绑定拖拽后再添加到列表
            var newSportLi = $('<li>' + sport + '</li>');
            newSportLi.draggable({ helper: "clone" }).css("cursor", "pointer");
            $("#sportList").append(newSportLi);
        }
    });

    // 初始绑定:给页面加载时的占位li添加拖拽
    $("#sportList li").draggable({ helper: "clone" }).css("cursor", "pointer");

    $("#step2Btn").click(function () {
        $('#step2').show();
    });

    //allows the sport items to be dropped into the cart
    $("#cart").droppable({
        tolerance: "intersect",
        drop: function (evt, ui) {
            var obj;
            $("#cart").css("height", "auto");
            obj = ui.draggable;
            console.log("dropped!");
            $("#cart").append("<li>" + obj.html() + " (<a href='dummy.html' class='remove'>Remove</a>)" + "</li>");
        }
    });

    //able to remove a sport item
    $("#cart").on("click", "a.remove", function () {
        console.log("Remove element!");
        $(this).parent().remove();
        return false;
    });

    getCart = function () {
        var cartList, el, group1;
        cartList = [];
        $("#cart li").each(function () {
            el = $(this).html();
            console.log("Matching element " + el);
            group1 = el.match(/^(.+) \(&lt;a href/)[1]
            console.log("Match with reg exp: " + group1);
            cartList.push(group1);
        })
        return cartList;
    }
});

额外说明

  • 初始的$("#sportList li").draggable(...)必须保留,用来给页面加载时的占位列表项绑定拖拽。
  • 如果后续有大量动态添加元素的场景,也可以用事件委托思路:监听元素的mouseover事件,当元素被hover时检查是否已绑定draggable,未绑定则添加。不过对你当前的场景,直接给新元素绑定更简洁高效。

内容的提问来源于stack exchange,提问作者Frank

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 09:00:05