简体   繁体   English

jQuery .insert仅在使用类选择器后一次

[英]jQuery .insertAfter only once with a class selector

I have the following code that is working correctly to insert a success span after an input field when a correct value is entered. 我有以下代码可以正常工作,以便在输入正确值时在输入字段后插入成功跨度。 But my problem is that it adds the span every time I leave the field. 但是我的问题是,每次我离开田野时,它都会增加跨度。 From question Jquery insertAfter only once if element exist I know that I could set the ID of the span when created and check the length each time the event fires to see if it already exists. 从问题Jquery insert仅在元素存在后一次,我知道我可以在创建时设置跨度的ID,并在每次事件触发时检查其长度以查看其是否已经存在。 But am not sure how to do that when using a class to select the fields. 但是不确定使用类选择字段时该如何做。

Any help with class selectors would be helpful. 类选择器的任何帮助将是有帮助的。

$(".systemFieldName").blur(function(){
          var val = $(this).val();
          var exists = $.inArray(val,allFields);  
    if (val!="" && exists>=0){
      $("<span class='label label-success'>Valid</span>").insertAfter(this).one();
    } 
});

Try this fiddle: https://jsfiddle.net/8jpc74z8/ 试试这个小提琴: https : //jsfiddle.net/8jpc74z8/

All I am doing here is to check whether there is any sibling to the systemFieldName already added. 我在这里所做的只是检查是否已经对systemFieldName添加了任何同级。 If not, then add. 如果不是,则添加。

 if($(".systemFieldName +.label-success").length === 0){

This should help. 这应该有所帮助。

allFields=["121",'test'];
$(".systemFieldName").blur(function(){
          var val = $(this).val();
          var exists = $.inArray(val,allFields);
          //See if the next element is a span with class label.
          var nextEl=$(this).next(); //next element
          var add=true; //add by default 
          if(nextEl.hasClass('label-success')) add=false; //don't add.

    if (val!="" && exists>=0 && add){ //only insert if all conditions are true.

      $("<span class='label label-success'>Valid</span>").insertAfter(this).one();
    }else if((val == "" || exists < 0) && !add) { // The !add means there is already the Valid span, we can safely remove nextEl, if the value changes.

      nextEl.remove();
    } 
});

https://jsfiddle.net/ym66f48p/2/ https://jsfiddle.net/ym66f48p/2/

This checks to make sure the next element is a span, it also includes a remove function that if the value is altered later on, it will remove the valid span, but ONLY if the next element is already a valid span. 这将检查以确保下一个元素是一个跨度,它还包括一个remove函数,如果以后更改该值,它将删除有效跨度,但是仅当下一个元素已经是一个有效跨度时才删除。

use 121 or test as your testing in the jsFiddle. 使用121或test作为jsFiddle中的测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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