简体   繁体   中英

How Jquery tag “insertAfter” display only once if element exist no repeat again and again?

Please suggest to me an answer for my question: how Jquery tag "insertAfter" display only once if element exist no repeat again and again?

$(document).ready(function (){$(".ddd").keypress(function (e) {

 if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
    $("<span style='color:red'>insert only character</span>").insertAfter( $(this)).show().fadeOut("slow");   
     return false;
}
 });
 });

Try using jQuery's .length property on your selector to check if it exists. If it doesn't, insert it:

 $(document).ready(function() { $(".ddd").keypress(function(e) { if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) { if (!$("#err").length) $("<span id= 'err' style='color:red'>insert only character</span>").insertAfter($(e.target)); $("#err").show().fadeOut("slow"); return false; } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input class="ddd"></input> 

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