简体   繁体   中英

SlideDown() doesn't work with After() in jQuery

I want to add an element to a list and I want that it slide down when is added. But using after() method it doesnt work. Why?

Html code:

<ul id="myUL">
 <li> First Item <li>
 <li> Second Item <li>
 <li> Third Item <li>
 <li> Fourth Item <li>

Add

Js code:

$('#add').click(function(e){
  e.preventDefault();     
  $('li:last').after('<li> A New Item </li>').slideDown("slow");
});

Fiddle full code: http://jsfiddle.net/gxs46L0u/

First of all you need to close those li tags. HTML:

<ul id="myUL">
  <li> First Item </li>
  <li> Second Item </li>
  <li> Third Item </li>
  <li> Fourth Item </li>
</ul>

Then for the js here's a quick and dirty way to do it:

$('#add').click(function(e){
  e.preventDefault();     
  $('li:last').after('<li style="display:none"> A New Item </li>');
  $('li:last').slideDown("slow");
});

You add an element without showing it and in the next step the slideDown will make it appear.

Try this:

Jsfiddle: http://jsfiddle.net/sw9yLdt7/

<ul id="myUL">
  <li> First Item </li>
   <li> Second Item </li>
   <li> Third Item </li>
   <li> Fourth Item </li>
</ul>
<a id="add" href="#">Add</a>

USe this jquery:

$('#add').click(function(e){
    e.preventDefault();     
    $('<li> A New Item </li>').appendTo('#myUL').hide().slideDown();
});

demo

<ul id="myUL">
  <li> First Item </li>
  <li> Second Item </li>
  <li> Third Item </li>
  <li> Fourth Item </li>
</ul>
<a id="add" href="#">Add</a>

$('#add').click(function(e) {
  e.preventDefault();
  $('#myUL').append('<li> A New Item </li>');
});

Problem is your HTML is not closed properly close them and use append

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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