简体   繁体   中英

Issue with moving list items with jQuery

I've been trying to figure this out for about a day, but I haven't been making too much progress. I want to have two lists, and move list items between them by double-clicking. I can get it to work if I have one event be "click", and the other "dblclick", but that's not what I want. If I attach "dblclick" events in both methods, the list items won't move and will just reorder themselves in the current list. Here's a JSFiddle that demonstrates my problem. I currently have it setup so one event is "click" and the other is "dblclick". If you change the parameter in the live function to "click" so it matches the other handler you'll see the issue I've been having.

HTML

<div id="orig">
<ul>
    <li class="original">one</li>
    <li class="original">two</li>
    <li class="original">three</li>
</ul>
</div>
<div id="moved">
    <ul>

    </ul>
</div>

CSS

#orig {
    width: 40%;
    height: 300px;
    overflow: auto;
    float: left;
    border: 1px solid black;
}

#moved {
    width: 40%;
    height: 300px;
    overflow: auto;
    float: right;
    border: 1px solid black;
}

jQuery

$(function() {
    $(".original").click(function(){
        this.className = "moved";
        $("#moved ul").append(this);
    });

    $(".moved").live("dblclick", function() { 
        this.className = "original";
        $("#orig ul").append(this);
    });

});

Here is a JSfiddle

You can make use of on method, live is already deprecated:

$("#orig").on("dblclick", "li", function() {
    $("#moved ul").append(this);
});

$("#moved").on("dblclick", "li", function() {
    $("#orig ul").append(this);
});

http://jsfiddle.net/zmnAm/6/

Plus you can also make it even shorter if you set a class to your div containers:

$container = $('.container').on('dblclick', 'li', function(e) {
    $container.not(e.delegateTarget).find('ul').append(this);
});

http://jsfiddle.net/zmnAm/7/

When you apply your eventhandlers to your listitems, they stay onto those elements the whole time. When you click an item on the left item, then click that same item on the right list, it'll still be the same item, with the same eventhandler you clicked on, so it'll still be moved to the right one, which it's already in.

You'll probably have to remove the original handler from the item you just clicked, and attach the other one to the item.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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