简体   繁体   中英

Adding 'LI' Element before the last LI tag

After clicking on "Add Comment" button, I want <li> </li> to be added at the end but before the last <li> .

See the code:

<div class="newsComment">
  <ul class="CommentReplies">
     <li class="Heading">
       <h3> Comments </h3>
     </li>
      <li class="CommentRow"> Comment 1 </li>
      <li class="CommentRow"> Comment 2 </li>
      // ADD LI HERE WHEN CLICKING ON THE BUTTON
     <li class="CommentRow">
      <form id="FormAddComment">
       <input name="comment" type="text" />
       <input id="submit_AddNewsComment" type="submit" value="Add Comment" />
       </form>
     </li>
   </ul>
</div>


$("#FormAddComment").submit(function() {
    data =  $(this).serialize();
    //Add LI
    return false;
});

Because the form is inside the li , use closest to find it, then before to insert in front of it.

$("#FormAddComment").submit(function() {
    var $this = $(this);

    data =  $this.serialize();

    //Add LI
    $this.closest("li").before(
        "<li>New content</li"
    );

    return false;
});

$(this).closest('.CommentRow').before($('<li />')); should do it.

$("#FormAddComment")提交函数中,这将插入<li>

$(this).closest('.CommentReplies').find('li:last').prepend('<li>Comment 3</li>');

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