2014-02-15 45 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 = ['.',':'] ;