0

我有以下函数来获取 ID 为 #posttext 的文本区域中的值并调用函数来发布内容。

我不希望用户能够连续输入多个换行符。我怎样才能防止这种情况?

这是代码:

//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;
}
}
});
4

1 回答 1

0

如果您稍后简单地删除重复的换行符会更好,例如使用这个正则表达式:s/\n{2,}/\n/g

但是,要做你想做的,只需删除重复的换行符 onkeyup

$('#postDiv').on('keyup', '#posttext', function(e) {
    var val = $(this).val(),
        newval = val.replace(/\n{2,}/g, '\n');
    if(val != newval) {
        $(this).val(newval);
    }
});

演示:http: //jsfiddle.net/ThiefMaster/WJmhF/

于 2012-05-08T09:50:26.607 回答