我有以下函数来获取带有id #posttext的textarea中的值,并调用函数来发布内容。
我不希望用户能够在一行中输入多个换行符 。我该如何防止这种情况?
以下是代码:
//Post something
$('#postDiv').on('keydown', '#posttext', function(e) {
if (e.which==13 && !e.shiftKey && $('#posttext').val()!=' Post something...') {
//This is what I tried to prevent a user from inserting more than one br in a row
var last = false;
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) {
if (last) { e.preventDefault(); }
last=true;
}else{
last=false;
}
//If not currently loading and enough text typed in, submit
if($('#imageFeedback').html()!=' | Loading...' && $('#posttext').val().length>15){
//Say that it is loading
$('#imageFeedback').css('color','black').css('font-weight','normal').html(' | Loading...');
//Call function to post
post($(this));
return false;
}
}
});
答案 0 :(得分:0)
如果您稍后删除重复的换行符会更好,例如使用此正则表达式:s/\n{2,}/\n/g
但是,要做你想做的事,只需删除onup上的重复换行符
$('#postDiv').on('keyup', '#posttext', function(e) {
var val = $(this).val(),
newval = val.replace(/\n{2,}/g, '\n');
if(val != newval) {
$(this).val(newval);
}
});