【问题标题】:How to append in multiple element JQuery如何追加多个元素JQuery
【发布时间】:2016-07-01 18:28:01
【问题描述】:

我有一个这样的 HTML:

<span class="section2 section4">hello</span>
<span class="section1">World</span>

<div class="tab" id="tab1"></div>
<div class="tab" id="tab2"></div>
<div class="tab" id="tab3"></div>
<div class="tab" id="tab4"></div>
<div class="tab" id="tab5"></div>

我需要一个能够给我这个结果的 jquery 函数:

<div class="tab" id="tab1"><span class="section1">World</span></div>
<div class="tab" id="tab2"><span class="section2">hello</span></div>
<div class="tab" id="tab3"></div>
<div class="tab" id="tab4"><span class="section4">hello</span></div>
<div class="tab" id="tab5"></div>

到目前为止我的尝试:

$.each($(".tab"), function() {
    var id = $(this).attr('id').substring(3);

    if ($(".section" + id).length == 0) {
        return true;
    }
    $(".section" + id).removeClass("section" + id).appendTo($(this));
})

我怎样才能改进我的功能以正确工作?

JSFiddle

【问题讨论】:

标签: javascript jquery


【解决方案1】:

遍历 div 并根据 id 中的数字附加克隆的 span 元素。使用 append() method with callback 迭代元素并附加回调返回值。

// get all span with classname start with `section`
var $sec = $('span[class^=section]');

// iterate over div element and append the returned value
$('div.tab').append(function() {
  // generate the class name from id
  var cls = 'section' + this.id.match(/\d+$/)[0];
  // filter element from $sec
  return $sec.filter('span.' + cls)
    // clone the element
    .clone()
    // updaet the class to remove other class name
    // you can also use `prop('className',cls)`
    .attr('class', cls);
});

// remove the span elements from dom
$sec.remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="section2 section4">hello</span>
<span class="section1">World</span>

<div class="tab" id="tab1"></div>
<div class="tab" id="tab2"></div>
<div class="tab" id="tab3"></div>
<div class="tab" id="tab4"></div>
<div class="tab" id="tab5"></div>

更新:如果您想维护其他类或跨度,请执行类似的操作。

// get all span with classname start with `section`
var $sec = $('span[class^=section]');

var $tab = $('div.tab');

// generate classnames based on tabs for removing later
var remove = $tab.map(function() {
  return 'section' + this.id.match(/\d+$/)[0];
}).get().join(' ');

// iterate over div element and append the returned value
$tab.append(function() {
  // generate the class name from id
  var cls = 'section' + this.id.match(/\d+$/)[0];
  // filter element from $sec
  return $sec.filter('span.' + cls)
    // clone the element
    .clone()
    // remove other class name
    .removeClass(remove).addClass(cls);
});

// remove the span elements from dom
$sec.remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="section2 section4">hello</span>
<span class="section1 section8">World</span>

<div class="tab" id="tab1"></div>
<div class="tab" id="tab2"></div>
<div class="tab" id="tab3"></div>
<div class="tab" id="tab4"></div>
<div class="tab" id="tab5"></div>

【讨论】:

  • 它正确地附加了容器中的项目,但是你没有在容器的函数中编辑类
  • 我知道我没有具体说明问题,但是如果 span 有其他类然后是“sectionX”,你可以编辑,在最终结果中我想保留这个其他类。如果你不能没有问题。并感谢您的帮助
  • @A.Rossi :为此你可以这样做:jsfiddle.net/pranavcbalan/a4nsdrje
【解决方案2】:

您的代码中的问题是您只是删除了原始元素并附加到类似的 id div 和 section2section4 跨度相同,因此当脚本适用于第 4 个 div 时,它会从第 2 个元素中删除并附加到第 4 个.

您需要使用.clone() 并让原始跨度位于原处,只需克隆它并附加到尽可能多的 div 上,然后使用 css 隐藏初始跨度。

 $.each($(".tab"), function() {
   var id = $(this).attr('id').substring(3);

   if ($(".span_wrap .section" + id).length != 0) {
     $(".span_wrap  .section" + id).removeClass("section" + id).clone().appendTo($(this));
   }

 })
.span_wrap span {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="span_wrap">
  <span class="section2 section4">hello</span>
  <span class="section1">World</span>
</div>

<div class="tab" id="tab1"></div>
<div class="tab" id="tab2"></div>
<div class="tab" id="tab3"></div>
<div class="tab" id="tab4"></div>
<div class="tab" id="tab5"></div>

【讨论】:

    【解决方案3】:

    试试这样的脚本

    $.each($(".tab"), function() {
        var id = $(this).attr('id').substring(3);    
        $('span').each(function(){
            var str = $(this).attr('class');
            var str1 = str.toString();
           if(str1.indexOf('section'+id) > -1){           
               $("#tab"+id).append("<span class='section"+id+"'>"+$('.section'+id).text()+"</span>");
           } 
        });
    }); 
    

    【讨论】:

      【解决方案4】:

      demo link

       $.each($(".tab"), function() {
         var id = $(this).attr('id').substring(3);
      
         if ($(".section" + id).length == 0) {
           return true;
         }
         var _this = $(this);
         var _section = $(".section" + id);
         _section.removeClass("section" + id);
         var _clonedSection = _section.clone();
         _clonedSection.appendTo(_this);
         _this.appendTo('#conteiner');
      
       })
       $("#tmp").remove();
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <div id="conteiner">
      </div>
      
      <div id="tmp">
        <span class="section2 section4">hello</span>
        <span class="section1">World</span>
      
        <div class="tab" id="tab1"></div>
        <div class="tab" id="tab2"></div>
        <div class="tab" id="tab3"></div>
        <div class="tab" id="tab4"></div>
        <div class="tab" id="tab5"></div>
      </div>

      结果 html:

      <div id="conteiner">
        <div class="tab" id="tab1"><span class="">World</span></div>
        <div class="tab" id="tab2"><span class="">hello</span></div>
        <div class="tab" id="tab4"><span class="">hello</span><span class="">hello</span></div>
      </div>
      

      【讨论】:

        【解决方案5】:

        如果你正在使用支持 .prop() 的新版本的 jQuery,试试这个:

        var origSections=[];
        $.each($(".tab"), function() {
            var id = $(this).prop('id').substring(3);
            var sections=$(".section" + id);
            if (sections.length === 0) {
                return true;
            }
        
            sections.each(function(){
                origSections.push($(this));
                var section=$(this).clone();
                section.removeClass().addClass("section" + id);
                section.appendTo($('#tab'+id));
               });
        });
        $.each(origSections,function(){
          $(this).remove();
        });
        

        否则,试试这个:

        var origSections=[];
        $.each($(".tab"), function() {
            var id = $(this).attr('id').substring(3);
            var sections=$(".section" + id);
            if (sections.length === 0) {
                return true;
            }
        
            sections.each(function(){
                origSections.push($(this));
                var section=$(this).clone();
                section.removeClass().addClass("section" + id);
                section.appendTo($('#tab'+id));
               });
        });
        $.each(origSections,function(){
          $(this).remove();
        });
        

        【讨论】:

          【解决方案6】:

          可能有两种情况描述如下:

          案例一:

          如果附加的divid 连续增加,即tab1, tab2, tab3 ...,那么您可以利用每个元素的"index"

          下面是完成任务的优化代码。

            $.each($(".tab"), function(index) {
               element_index = ++index;
               if ( $('.section'+ element_index ).length ){
                  html_text = $(".section"+element_index).html();
                  $(this).html('<span class="section">'+html_text+'</span>');
               }
            }); 
          

          案例 2:

          如果附加的divid 没有连续增加,即tab1, tab5, tab3, tab6 ...,那么您需要检查这两个元素是否存在。

          下面是完成任务的优化代码。

          $.each($(".tab"), function(index) {
          	element_id = $(this).attr('id').slice(-1);
          	if ( $('.section'+ element_id ).length ){
          		html_text = $(".section"+element_id).html();
          		$(this).html('<span class="section">'+html_text+'</span>');
          	}
          }); 
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
          
          <span class="section2 section4">hello</span>
          <span class="section1 section6">World</span>
          
          <div class="tab" id="tab1"></div>
          <div class="tab" id="tab6"></div>
          <div class="tab" id="tab3"></div>
          <div class="tab" id="tab4"></div>
          <div class="tab" id="tab5"></div>

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2012-03-05
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-05-12
            • 2013-02-25
            • 1970-01-01
            相关资源
            最近更新 更多