2014-02-15 44 views
0

我写了一个简单的函数:插入消息只有一次()

if (some "charCode" is entered into <input>) { 
// display warning message 
} 

问题是,如果你重复输入禁则charCode时,消息被反复插入过。我需要它来显示只有一次,所以我嵌套在另一个“如果”:

if (some "charCode" is entered into <input>) { 
        if (warning does not exist in the DOM) { 
        // insert the message 
       } else { 
        //remove message and re-insert 
      } 
    } 

这里是一个错误的代码:

$(document).ready(function() { 

    $('input').keypress(function (key) { 
     var Warning = '<div class="exerciseWarning"><p>Warning msg</p></div>'; 
     if (key.charCode === 46 || key.charCode === 44) { 
      if (Warning.length !== 0) { 
       $('input').after(Warning); 
       return false; 

      } else { 
       Warning.remove(); 
       $('input').after(Warning); 
      } 
     } 
    }); // end of keypress() 

    //last bracket 
}); 

和提琴在这里 - >Fiddle

回答

1

您正在检查字符串文字Warning的长度永远不会为0.您可以检查当前输入元素的下一个兄弟元素是否为exerciseWarning元素,如下所示

尝试

$(document).ready(function() { 

    var Warning = '<div class="exerciseWarning"><p>Warning msg</p></div>'; 
    $('input').keypress(function (key) { 
     if (key.charCode === 46 || key.charCode === 44) { 
      var $this = $(this); 
      if (!$this.next().is('.exerciseWarning')) { 
       $('input').after(Warning); 
       return false; 
      } 
     } 
    }); // end of keypress() 

    //last bracket 
}); 

演示:Fiddle

+0

谢谢。它完美的作品。 – Andrejs

0
$(document).ready(function() { 

     $('input').keypress(function (key) { 
      var Warning = '<div class="exerciseWarning"><p>Warning msg</p></div>'; 
      if (key.charCode === 46 || key.charCode === 44) { 
       if ($('.exerciseWarning').length <= 0) { 
        $('input').after(Warning); 
        return false; 

       } else { 
        // $('.exerciseWarning').remove(); 
        //$('input').after(Warning); 
       } 
      } 
     }); // end of keypress() 

     //last bracket 
    }); 

    // var stupidPunctuation = ['.',':'] ;