简体   繁体   中英

jQuery last-child selector not “refreshing”

On the last textarea box on the page a function is called to insert another textarea box. Making it the new last textarea, however jQuery does not see this textarea being the new last textarea.

The function sticks on the last textarea that was inserted via html.

 function add_new() { $('.edit_main').append('<li><div class="edit_one"><textarea class="text1"></textarea></div><div class="edit_two"><textarea class="text2"></textarea><textarea class="text3"></textarea></div><div style="clear:both;"></div></li>'); } $(".edit_main li:last-child div.edit_two textarea:last-child").keydown(function(e) { var code = e.keyCode || e.which; if (code == 9) { add_new(); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ol class="edit_main"> <li> <div class="edit_one"> <textarea class="text1"></textarea> </div> <div class="edit_two"> <textarea class="text2"></textarea> <textarea class="text3"></textarea> </div> <div style="clear:both;"></div> </li> <li> <div class="edit_one"> <textarea class="text1"></textarea> </div> <div class="edit_two"> <textarea class="text2"></textarea> <textarea class="text3"></textarea> </div> <div style="clear:both;"></div> </li> </ol> 

jsfiddle

This is a one-time selector. In order to get it to dynamically update, you need to use event delegation .

$(document).on("keydown", ".edit_main li:last-child div.edit_two textarea:last-child", function (e) {
  if (e.which == 9){
    add_card();
  }
});

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