jQuery插入最后一个元素之后

时间:2014-11-19 07:59:57

标签: javascript jquery html

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

<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();然后在最后一次之后插入

7 个答案:

答案 0 :(得分:15)

只需要last()方法

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

答案 1 :(得分:5)

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

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

这当然意味着你的第一个元素也必须有类:

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

答案 2 :(得分:1)

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

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

答案 3 :(得分:1)

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

上试试自己

答案 4 :(得分:0)

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

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

答案 5 :(得分:0)

您可以尝试下面的代码,它会在最后一个“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'));
        }
    });
});

答案 6 :(得分:0)

**希望这会使您更加了解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>