【问题标题】:jQuery insert after the last elementjQuery 在最后一个元素之后插入
【发布时间】:2015-01-16 16:03:15
【问题描述】:

我想在最后一个之后添加元素。 我当前的代码

<div class="find"><div id="FirstElement"> /*First element loaded first */ </div><div>

$('#AddNextElement' + id).click(function (e) {
   $('<div id="NextElement' + id +'">' + /*Add after the last element*/ + '</div>').insertAfter($("#FirstElement"));
}

当前它只在第一个元素之后添加它:

1 4 3 2

我希望它每次都在最后一个元素之后添加:

1 2 3 4

我已经点击了这些链接,但没有找到我要查找的内容:

jQuery insertAfter last item

insertAfter specific element based on ID

jQuery: Add element after another element

提前谢谢你!

我是如何解决的:

$('#AddNextElement' + id).click(function (e) {
   $('<div id="NextElement"' + id +'>' + /*Add after the last element*/ + '</div>').insertAfter($("#FirstElement").parent().find('.Finder').last());
}

我找到了 .parent().find('.find').last();然后插入到最后一个

【问题讨论】:

  • 你为什么不能简单地使用.append()
  • .append() 会让你的工作完成
  • "NextElement"' + id +' 此代码返回 "NextElement"0 "NextElement"1 ecc... 我认为这样更好:"NextElement' + id +'" return "NextElement0" "NextElement1" ecc...

标签: javascript jquery html


【解决方案1】:

只需要last()方法

$('<div id="NextElement"' + id +'>' + /*Add after the last element*/ + '</div>')
.insertAfter($('[id^="NextElement"]').last());

【讨论】:

  • 我尝试添加 .last() ,但仍然得到相同的结果!
  • 你用过[id^= ...吗?
  • 您对 .last() 的看法是对的...我需要先找到父级,然后再找到最后一个。谢谢
  • last() 应该在 insertAfter() 之前
【解决方案2】:

为所有元素添加一个类怎么样?找到最后一个会更容易:

$('.element-class:last').after('<div class="element-class" id="NextElement"' + id +'>' + /*Add after the last element*/ + '</div>');

这当然意味着您的 First 元素也必须具有类:

<div class="element-class" id="FirstElement"> /*First element loaded first */ </div>

【讨论】:

    【解决方案3】:

    查找 DOM 中的最后一个元素,在您的情况下,它将是 'NextElementxx',然后使用 'after':

    $('#NextElement2').after( ..new stuff.. );
    

    【讨论】:

      【解决方案4】:

      HTML:

      <div id="FirstElement"> First element loaded first  </div>
      
      <div id="AddNextElement">Click me</div>
      

      JS:

      var current = 0;
      $('#AddNextElement').click(function (e) {
          var $el = (current == 0) ? $("#FirstElement") : $("#NextElement"+current);
          current++;
          $('<div id="NextElement' + current +'">Other element '+current+'</div>').insertAfter($el);
      });
      

      试试jsfiddle

      【讨论】:

        【解决方案5】:

        一种方法是存储最后一个元素。

        <div id="FirstElement"> /*First element loaded first */ </div>
        
        var lastElement = $('#FirstElement');
        
        $('#AddNextElement' + id).click(function (e) {
            var element = $('<div id="NextElement"' + id +'>' + /*Add after the last element*/ + '</div>'));
            element.insertAfter(lastElement);
            lastElement = element;
        }
        

        【讨论】:

          【解决方案6】:

          你可以试试下面的代码,它会在最后一个“NextElement”div之后添加新的div

          JS 代码:

          $(function(){
              $('#AddNextElementButton').on("click", function (e) {
                  var id = $("[id^='NextElement']").length ? $("[id^='NextElement']").length+1 : 1;
          
                  if($("[id^='NextElement']").length){
                      $('<div id="NextElement'+ id +'">Add after the last element</div>').insertAfter($('[id^="NextElement"]').last());
                  } else {
                      $('<div id="NextElement'+ id +'">Add after the last element</div>').insertAfter($('#FirstElement'));
                  }
              });
          });
          

          【讨论】:

            【解决方案7】:

            **希望这能让你很好地理解 GitHub:Omar-baksh **

            // code by GitHub: omar-baksh 
            // jquery is required online !!
            
            
            							/*
            							//this scricp test if jquery loded 
            
            							window.onload = function() {
             							   if (window.jQuery) {  
             							       // jQuery is loaded  
             							       alert("Yeah!");
             							   } else {
             							       // jQuery is not loaded
             							       alert("Doesn't Work");
             							   }
            							}
            							*/
            
            var gfather = document.getElementsByClassName('Gfather');
            var father =  document.getElementsByClassName('father');
            var son = document.getElementsByClassName('son');
            
            
            function gf(argument) {
            $(gfather).mouseenter(function(){
            	for (let i = 0; i < father.length; i++) {
            		father[i].style.display='block';
            	};
            // show father fun() body show  body last ...
            
            });
            
            $(father).mouseenter(function(){
            	for (let i = 0; i < son.length; i++) {
            		son[i].style.display='block';
            	};
            // son show  body last ...
            });
            
            
            
            	// gf body last ...
            }
            
            // show form setting bottun fun()
            
            function add(){
            	 const x = document.getElementById("frm").style.display='block';
            	alert('setting opened');
            	
            }
            
            // form  add element fun()
            var clslist=document.getElementsByClassName("list");
            var inher =document.getElementById("level");
            var num =document.getElementById("num").value;
            var txt =document.getElementById("inp-text");
            // var add-btn = document.getElementById("btn-secsuce");
            
            /*
            $("#inher").change(function () {
            	alert(inher);
            	document.getElementById("inp-text")="you selected"+ document.getElementById("level").value;
            	// body...
            });
            */
            var clss ="";
            var ii;
            $( "#btn-secsuce" ).click(function () {    
            //txt.value="class name "+inher.value;  
                if( String(inher.value) =="Grand father"){
                  clss ="Gfather";
             jQuery('<div/>', {
                id: Math.ceil(Math.random() * 999),
                text:txt.value,
                "class": clss,
                title: clss+clss.length
            }).appendTo(clslist);
            
            	alert("add class "+inher.value+gfather.length);
            }
            
            
            else { // alert("class enhhert is roung you chose " +inher.value )
            	
            }
            
            
            /// add father to g father
            
            if( String(inher.value) =="father"){
             var txt2 = $("<div class="+"father"+"></div>").text(txt.value);
              $(father[num-1]).after(txt2);
            
            
            }
            
            else{
            	
            
            
            }
            
            
            });  
            .Gfather{
            	 width: 60px;
            	 height: auto;
            border-left: 6px dashed  red;
            border-bottom: 6px dashed  red;
              background-color: silver;
             top:0;
              display:block;
            position:relative ;
            margin-left:9px;
             white-space: nowrap;
            }
            
            .father{
            	 width: 60px;
                border-left: 6px dashed  red;
            border-bottom: 6px dashed  red;
             bottom:0;
              padding-top:0px;
            border-right-width: small;
            left:66px;
               white-space: nowrap;
            position:relative ;
            background-color: #550088;
            color:white;
            display: block;
            }
            <head>
              <title>tree js</title>
              <meta charset="utf-8">
              <link rel="stylesheet" type="text/css" href="./tree.css">
            </head>
            <body>
            <div class="list">
                  <div class ="Gfather" onmouseover="gf();">
                  grand father 1
                  
                  </div> 
                     <div class ="father">
                      father
                           
                      </div>
                    
                    
            
                        <div class ="son">son
                       </div>
                <div class ="son">son
                       </div>
               
                   
                      </div>
                      <!-- add element show setting btn -->
            
                      <button id="add" onclick="add()" > add setting</button>
            
                   <form id="frm">
            
                                                                 <h6>1</h6>
                       <select id="level">
                           <option>Grand father</option>
                           <option>father</option>
                           <option>son</option>
                           
                       </select>
            
                      
                                                                  <h6>2</h6> 
                       <select id="num">
                           <option>1</option>
                           <option>2</option>
                           <option>3</option>
                           <option>4</option>
                           <option>5</option>
                           <option>6</option>
                           <option>7</option>
                           <option>8</option>
                           <option>9</option>
                       </select>
                       <br>
                                                                   <h6>3</h6>
                        <input id="inp-text" type="text">
            
                                                             <h5 >4</h5>
                        <button type="button" id="btn-secsuce"  >Add The Element  </button>
                   </form>
                   <script
              src="https://code.jquery.com/jquery-3.4.1.js"
              integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
              crossorigin="anonymous"></script>
                   <script type="text/javascript" src="./tree.js"></script>

            【讨论】:

            • 请阅读how to write a good answer。带有描述“希望这会让你很好理解”的格式不正确的代码墙不太可能让某人很好理解。另外,如果不是您的代码,请添加参考原始代码的链接
            【解决方案8】:

            你可以用这个:

            jQuery('##AddNextElement').last().after();
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2019-05-05
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2013-12-27
              • 2011-01-16
              • 2015-01-21
              相关资源
              最近更新 更多