簡體   English   中英

如何將所有元素移動到另一個包裝元素?

[英]How can I move all elements to another wrapping element?

我有兩個列表( #product#cart )。 人們可以單擊一個項目並將其一次移至第二個列表。 但我希望允許人們將第一個列表中的所有項目添加到第二個列表中。 反之亦然–從購物車中刪除所有物品。

你能幫我嗎?

這是我的html:

<h2>Product List</h2>
<a id="add-all">Add all items to cart</a>
<ul id="product">
    <li id="item1">item 1</li>
    <li id="item3">item 3</li>
    <li id="item5">item 5</li>
</ul>

<h2>Shopping Cart</h2>
<a id="remove-all">Remove all items</a>
<ul id="cart">
    <li id="item2">item 2<input type="hidden" name="cartItems" value="item2"></li>
    <li id="item4">item 4<input type="hidden" name="cartItems" value="item4"></li>
</ul>

正如你可以在上面看到,當一個項目被單獨添加到購物車中,我.appendinput使用相同的ID標簽。

粗略的jQuery看起來像這樣:

$('#product').on('click','li', function() {
    var itemID = $(this).attr('id');
    var itemLabel = $(this).html();
    var newItemLabel = itemLabel + '<input type="hidden" name="cartItems" value="' + itemID + '">';
    $(this).remove();
    $('#cart').append('<li id="' + itemID + '">' + newItemLabel + '</li>');
});

一次只能工作一次。 但是我堅持嘗試遍歷產品列表中的每個項目以添加所有(或刪除所有)。

你能為我指出正確的方向嗎?

特別是因為我需要為每個列表項添加一個輸入元素。 因此,我不能只使用#producthtml()並追加到#cart而不循環遍歷每個代碼並追加輸入。

l

  1. #add-all點擊應將#product所有項目#product #cart ,並向每個項目添加input
  2. #remove-all點擊應將#cart所有項目#cart #product ,並刪除所有input標簽
  3. 怎么樣?

這將為所有工作

$('#add-all').on('click', function () {
    $(this).siblings('ul').find('li').each(function (index, item) {
    $(item).append("<input type=\"hidden\" name=\"cartItems\" value=\"" + $(item).attr('id') + "\"/>");
    $('#cart').append($(item));
  });
});

您可以按照類似的邏輯刪除全部。

檢查此小提琴: http : //jsfiddle.net/hcXpY/

檢查此小提琴以同時刪除所有代碼: http : //jsfiddle.net/hcXpY/2/

$('#remove-all').on('click', function () {
  $(this).siblings('ul').find('li').each(function (index, item) {
    $(item).find('input').remove();
    $('#products').append($(item));
  });
});

迭代怎么了?

$('#product li').each( function() {
    var itemID = $(this).attr('id');
    var itemLabel = $(this).html();
    var newItemLabel = itemLabel + '<input type="hidden" name="cartItems" value="' + itemID + '">';
    $(this).remove();
    $('#cart').append('<li id="' + itemID + '">' + newItemLabel + '</li>');
    removeDuplicatesFromCart();
});

function removeDuplicatesFromCart()
{
 //now remove any duplicates if there are in the carts
}

您可以執行以下簡單操作:

$("#add-all").click(function() {
    $("#products").children().appendTo("#cart");
});
$("#remove-all").click(function() {
    $("#cart").children().appendTo("#products");
});

然后,您可以在此添加添加/刪除<input>標記的代碼,或者只是始終顯示input標記,並在不在購物車中時通過CSS隱藏它。

嘗試為需要刪除的每個產品li添加一個remove類。 然后遍歷所有產品子級,如果li具有一類remove,則將其添加到購物車。

添加課程

$('ul#products li').click( function() {
    $(this).addClass('remove');
});  

循環播放

$('ul#products li').each( function() {
    if($(this).hasClass('remove')){
       $(this).appendTo('#cart');
    }
});

您需要一些東西來觸發上述按鈕嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM