1

我有这个函数,其中#text_comment 是文本区域的 ID:

$('#text_comment').live('keypress',function (e) {

    if(e.keyCode == 13) {
        textbox = $(this);
        text_value = $(textbox).val();

        if(text_value.length > 0) {
            $(this).prev().append('<div id="user_commenst">'+text_value+'</div>');
            $(textbox).val("");
        } 
    }                                               
});

发生的事情是当按下回车键(keyCode 13)时文本正在附加,但它也将文本向下移动一行,正如回车键应该做的那样。

即使我将文本框的值设置为“”,也​​会发生这种情况。

4

5 回答 5

4

event.preventDefault()怎么样

于 2011-06-15T09:05:04.843 回答
2

进入案例时,尝试停止您的事件传播(请参阅http://snipplr.com/view/19684/stop-event-propagations/ )。if(e.keyCode == 13)

于 2011-06-15T09:07:15.837 回答
2

试试这个event.stopImmediatePropagation()

$('#text_comment').live('keypress',function (e) {       
          if(e.keyCode == 13) {   
               e.stopImmediatePropagation()
       ///rest of your code
  }
});
于 2011-06-15T09:11:16.620 回答
2

我已经测试过了,这行得通。输入不会创建新行。

$('#text_comment').live('keypress',function (e) {

    if(e.keyCode == 13) {
        textbox = $(this);
        text_value = $(textbox).val();

        if(text_value.length > 0) {
            $(this).prev().append('<div id="user_commenst">'+text_value+'</div>');
            $(textbox).val("");
        }
        return false;
    }                                               
});

尽管我想知道,如果您不想换行,为什么要使用 textarea,为什么不使用 input type='text' 代替?

于 2011-06-15T09:20:02.130 回答
1

在这里回答http://jsfiddle.net/Z9KMb/

于 2011-06-15T09:34:48.420 回答