Javascript jQuery 在最后一个元素之后插入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27011723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:36:37  来源:igfitidea点击:

jQuery insert after the last element

javascriptjqueryhtml

提问by Norris

I want to add elements after the last one. My current code

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

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

Current it adds only it after the first element:

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

1 4 3 2

1 4 3 2

I want it to add after the last element every time:

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

1 2 3 4

1 2 3 4

I've followed these links and I didn't find what I'm looking for:

我已经点击了这些链接,但没有找到我要找的东西:

jQuery insertAfter last item

jQuery insertAfter 最后一项

insertAfter specific element based on ID

根据 ID 在特定元素后插入

jQuery: Add element after another element

jQuery:在另一个元素之后添加元素

Thank you in advance!.

先感谢您!。

How I fixed it:

我是如何修复它的:

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

I found the .parent().find('.find').last(); then insert after the last

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

回答by Bhojendra Rauniyar

Just you need last()method

只是你需要last()方法

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

回答by Thanasis Pap

How about adding a class to all elements? It will be easier to find the last:

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

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

This of course means that your First element must also have the class:

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

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

回答by Pat Dobson

Find the last element in the DOM, in your case it'll be 'NextElementxx' and then use 'after':

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

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

回答by Frogmouth

HTML:

HTML:

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

<div id="AddNextElement">Click me</div>

JS:

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

Try yourself on jsfiddle

jsfiddle上尝试一下

回答by Ashish Panchal

You can try below code, it will add the new div after the last "NextElement" div

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

JS Code:

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

回答by Omar bakhsh

**hope this will make you understand well GitHub:Omar-baksh **

**希望这能让你更好地理解 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>

回答by Smallcampus Tin

one way is to store the last element.

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

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