简体   繁体   English

如何在多元素JQuery中追加

[英]How to append in multiple element JQuery

I have a HTML like this : 我有这样的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>

I need a jquery function able to give me this result : 我需要一个能够给我这个结果的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>

My try so far : 我到目前为止的尝试:

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

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

How can i improve my function for correct work? 如何改进我的正确工作功能?

JSFiddle 的jsfiddle

Iterate over the divs and based on the number in id append the cloned span element. 迭代div并根据id中的数字附加克隆的span元素。 Use append() method with callback which iterates over the element and appends the callback return value. 使用带有回调的append()方法,方法遍历元素并附加回调返回值。

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

UPDATE : If you want to maintain the other class or the span, then do something like. 更新:如果你想维护其他类或跨度,那么做类似的事情。

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

The problem in your code is you are just removing the original element and appending to similar id div and for section2 and section4 span are same so when script works for 4th div it removes from 2nd element and append to 4th. 您的代码中的问题是您只是删除原始元素并附加到类似的id div,并且section2section4 span是相同的,因此当脚本适用于第4个div时,它将从第2个元素中删除并追加到第4个。

You need to use .clone() and let the original span be at it place just clone it and append on as much div as you want and hide the initial span with css. 你需要使用.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> 

Try script Like this 尝试脚本像这样

$.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>");
       } 
    });
}); 

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> 

result html: 结果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>

If you're using new versions of jQuery which support .prop() try this : 如果您正在使用支持.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();
});

Otherwise, try this one : 否则,试试这个:

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

There may have two Case Described bellow: 可能有两个案例描述如下:

Case-1: 情况1:

If the id of the appending div are serially increased ie tab1, tab2, tab3 ... then you can take the benefit of the "index" of each element. 如果追加divid连续增加,即tab1, tab2, tab3 ...那么你可以利用每个元素的"index"

Bellow is the optimized code to do the task. Bellow是完成任务的优化代码。

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

Case-2: 案例2:

If the id of the appending div are not serially increased ie tab1, tab5, tab3, tab6 ... then you need to check existence of both the element. 如果附加divid没有连续增加,即tab1, tab5, tab3, tab6 ...那么你需要检查这两个元素是否存在。

Bellow is the optimized code to do the task. Bellow是完成任务的优化代码。

 $.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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM