2012-04-15 82 views
0

我有一組按鈕,我正在爲動態添加按鈕。我的選擇會是這個樣子:如何在追加到另一個元素之前使用Jquery/Javascript從選擇中刪除元素?

$elements = [a.midToggle, a.menuToggle, a.ui-crumbs] 

我想這個選擇預先考慮到現有controlgroup:

<div data-role="controlgroup" data-type="horizontal" class="dropZone"> 
    <a href="#" class="some">Some</a> 
    <a href="#" class="midToggle">MidTog</a> 
</div> 

但前面加上之前,我想從我的選擇已經刪除controlgroup裏面的按鈕,否則他們會在那裏多次。

我想這樣的,但它並沒有在所有的工作:

// I have multiple controlgroups, so I need to add the buttons to all of them 
$('.dropZone').each(function() {  

    var $first = $(this), 
    $buttons = $elements.clone(); 

    $buttons.each(function() { 
    // check if class name on new button is already in controlgroup 
    if ($(this).is(".midToggle") && $first.find(".midToggle").length > 0) { 
    $(this).remove(); 
     } 
     if ($(this).is(".menuToggle") && $first.find(".menuToggle").length > 0) { 
    $(this).remove(); 
     } 
     if ($(this).is(".ui-crumbs") && $first.find(".ui-crumbs").length > 0) { 
    $(this).remove(); 
     } 
     }); 
// append what's left 
$first.append($buttons) 

我認爲我的$按鈕不會被刪除,但我不知道如何得到它工作。我的三個if語句也有些蹩腳。有一個更好的方法嗎?

編輯:
我不得不modifiy解決一點,因爲每個按鈕都有多個類,所以我不能簡單地檢查ATTR(「類」)。這不是完美的,但工作原理:

function clearOut($what) { 
    $buttons.each(function() { 
     if ($(this).is($what)) { 
      $buttons = $buttons.not($what) 
      } 
     }); 
    } 

// filter for existing buttons 
// TODO: improve 
if ($first.find('.midToggle')) { 
    clearOut('.midToggle'); 
    } 
if ($first.find('.menuToggle')) { 
    clearOut('.menuToggle'); 
    } 
if ($first.find('.ui-crumbs')) { 
    clearOut('.ui-crumbs'); 
    } 
+0

爲什麼不能讓他們都在那裏,只是'隱藏()'/'顯示() 「他們? – 2012-04-15 16:35:01

+0

@lila G:也想過這個,但是那裏可能會有按鈕,這些按鈕會隨着我在哪個頁面而不斷變化。以上三點是不變的。也許應該給這個更多的想法。 – frequent 2012-04-15 16:41:04

+0

首先從控件元素中刪除所有按鈕,然後只需添加任何你想要的按鈕,會比較容易... – 2012-04-15 16:49:53

回答

1

我尖叫着你的代碼到一半:

$('.dropZone').each(function() { 
    var $dropZone = $(this); 
    var $buttons = $elements.clone(); 
    $buttons.each(function() { 
     var $button = $(this); 

     if ($dropZone.find('.' + $button.attr('class')).length) 
      $button.remove(); 
    }); 

    $dropZone.append($buttons); 
});​ 
+0

啊。這看起來不錯。試。 – frequent 2012-04-15 16:54:58

+0

@頻繁。這不是困擾我的重要問題。我只是好奇,爲什麼人們不接受答案而不接受答案。無論如何,我很樂意提供幫助。 – gdoron 2012-04-15 17:09:30

+0

你有一點。另請參閱我的回答 – frequent 2012-04-15 17:11:32

0
$('.dropZone').each(function() {  
    $buttons = $elements.filter(function() { 
     if ($('.'+this.className).length) return this; 
    }); 
    $(this).append($buttons); 
}); 
相關問題