简体   繁体   中英

JQuery: Using .last() with a created element in a .on

I'm currently making a tab structure similar to Google Chrome. I have recently made a "New Tab" button and function that adds a new tab. Right now my function only creates one tab. My code bases where the next tab elements will go in the HTML tree by using $(".tab-clickable").last().after() . The last .tab-clickable element represents the last part of the closest tab.

Here is my code: https://codepen.io/lectrician1/pen/baOxdO

I originally was using a .click event but switched to .on because I figured that there was an problem finding the the tab last created. So I ran a debugging test and apparently the .on wasn't the problem but the $(".tab-clickable").last().after() was. But remember, my code still creates a tab, only just one though. I think the issue has to deal with finding the last .tab-clickable element that was just created in the first tab made.

Please post the relevant part of your code in the question next time you ask, or edit your post.

You're determining the position of the new tab using the tabAmount variable which you initially set to 2. However, when you add a new tab, at no point do you increase this variable. Your code is producing new tabs, but they're just all being put in the same place over each other.

All you need to fix the problem is add tabAmount++ to the end of the function (and decrement it if you remove a tag, or take it from the length each time)

Main problem is you are checking tabAmount only on page load. Need to check it each time you want to add another to get updated count

Move :

var tabAmount = $(".tab-clickable").length;

Into

$("#button").on("click", function() {
   var tabAmount = $(".tab-clickable").length;
   // other code remains same

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