如何在追加到另一个元素之前使用 Jquery/Javascript 从选择中删除一个元素

how to remove an element from a selection using Jquery/Javascript before appending to another element?

本文关键字:元素 删除 Javascript 选择 一个 Jquery 追加 另一个      更新时间:2023-09-26

我有一组按钮,我正在动态添加按钮。我的选择将如下所示:

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

我想将此选择附加到现有控制组:

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

但是,在预置之前,我想从我的选择中删除控制组中已有的按钮,否则它们将多次出现在那里。

我正在尝试这样做,但它根本不起作用:

// 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 ) 

我认为我的$buttons没有被删除,但我不知道如何让它工作。另外,我的三个如果陈述有点蹩脚。有没有更好的方法可以做到这一点?

编辑:
我不得不稍微修改解决方案,因为每个按钮都有多个类,所以我不能简单地检查 attr('class')。这并不完美,但有效:

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');
    }

我尖叫着把你的代码分成两半:

$('.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);
});​
$('.dropZone').each(function() {     
   $buttons = $elements.filter(function() {
       if ($('.'+this.className).length) return this;
   });
   $(this).append( $buttons );
});