本文介绍了从列表到列表jQuery添加和删除项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在单击时从一个列表到另一个列表添加和删除项目.这是小提琴

I need to add and remove items from one list to another on click. Here is fiddle

想法是,在添加"按钮上单击<li>Item</li>进入第一名的第二个列表,在移除"按钮上单击<li>Item</li>进入第一名的第一名.

Idea is that on "Add" button click <li>Item</li> goes to second list on first place and that on "Remove" button click <li>Item</li> goes to first list on first place.

我想要一个可以多次单击按钮并将项目从一个列表移到另一个列表的选项.

I want option that I can click several times on buttons and move items from list to list.

HTML:

<ul id="listOne">
    <li>Item 1 <button type="submit" id="add">Add</button></li>
    <li>Item 2 <button type="submit" id="add">Add</button></li>
    <li>Item 3 <button type="submit" id="add">Add</button></li>
</ul>

<ul id="listTwo">
    <li>Item 4 <button type="submit" id="remove">Remove</button></li>
    <li>Item 5 <button type="submit" id="remove">Remove</button></li>
    <li>Item 6 <button type="submit" id="remove">Remove</button></li>
</ul>

jquery :(我的知识不多)

Jquery: (I have low-knowledge)

function moveItems(origin, dest) {
  $(origin).find('li').appendTo(dest);
}
$('#add').click(function () {
    moveItems('#listOne', '#listTwo');
});

$('#remove').on('click', function () {
    moveItems('#listTwo', '#listOne');
});

推荐答案

您可以通过将li元素附加到当前不是其子元素的ul来简化逻辑.您还可以通过读取要附加到其上的父列表上的data属性来设置按钮的文本.最后请注意,在文档范围内重复相同的id是无效的,您应该使用类对元素进行分组.试试这个:

You can simplify the logic by appending the li element to the ul which it currently not a child of. You can also set the text of the button by reading a data attribute on the parent list you're appending to. Finally note that having the same id repeated in the scope of a document is invalid, and you should use classes to group elements instead. Try this:

<ul id="listOne" class="list" data-button-text="Add">
    <li>Item 1
        <button type="button">Add</button>
    </li>
    <li>Item 2
        <button type="button">Add</button>
    </li>
    <li>Item 3
        <button type="button">Add</button>
    </li>
</ul>

<ul id="listTwo" class="list" data-button-text="Remove">
    <li>Item 4
        <button type="button">Remove</button>
    </li>
    <li>Item 5
        <button type="button">Remove</button>
    </li>
    <li>Item 6
        <button type="button">Remove</button>
    </li>
</ul>
$('.list button').click(function() {
    var $list = $(this).closest('.list');
    var $targetList = $('.list').not($list)
    $(this).closest('li').appendTo($targetList);
    $(this).text($targetList.data('button-text'));
})

小提琴示例

请注意,同一事件处理程序使用共享类对两个列表均有效.

Note that this same event handler works for both lists using a shared class.

这篇关于从列表到列表jQuery添加和删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 01:42