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
謝謝。它完美的作品。 – Andrejs