1

您好,这是我文件头中的内容:

function entsub(event)
        {
              if (event && event.which == 13) 
                write1();
              else
            return true;

        }

在体内,我的形式是:

<form id="writeform" name="writeform">
  Message: <br />
  <textarea name="message" rows="3" id="message" style="width:90%;" onkeypress="return entsub(event)"></textarea>

  <br />
  <input name="send" type="button" id="send" value="Send" onclick="write1()" />
  <span id="sent"></span>
  &nbsp;&nbsp;&nbsp; <input type="reset" value="Reset" />
  </form>

我需要让它工作,当我在 textarea 中按 Enter 时,它不会换行而是发送它[见我的<input type="button">]

但它不会工作!它不断创造新的路线......现在使用IE8。

4

6 回答 6

2

好吧,我不确定是什么write1(),但是在满足条件时返回 false 是谨慎的。

function entsub(event)
{
    if (event && event.keyCode == 13) {
        write1();
        return false; //Return false to prevent default execution
                      //Some browsers use event.preventDefault() etc.
    }else{
        return true;
    }
}
于 2009-10-26T18:37:44.773 回答
2

通常跨浏览器测试如下:

function entsub(e) {
    if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
        write1();
    } 
    return true;
}
于 2009-10-26T18:44:23.903 回答
2

如果你想使用 jquery,你可以这样做:

        $(document).ready(function() {

            $("#txtTest").keypress(function(e) {
                var code = (e.keyCode ? e.keyCode : e.which);

                if (code == 13) {
                    doSomething();
                    return false;
                }
            });

        });

        function doSomething() {
            alert("I did it!");
        }

其中 txtTest 是您的文本区域的 id。

于 2009-10-26T18:49:10.507 回答
1

使用 keyCode 而不是 which。

根据浏览器,您需要阻止默认操作。查看 IE 的 event.cancelBubble 和 event.returnValue 以及 Firefox 的 event.stopPropagation() 和 event.preventDefault()。

于 2009-10-26T18:38:58.453 回答
0

对于非 js 相关的方式,我很确定您可以只使用 type="submit" 的输​​入,它将使用 enter 提交表单。那时,您只需将您的活动移至 onsubmit。

于 2009-10-26T19:00:21.187 回答
0

一种更简洁的方法是在表单上更改为<input type="button">to<input type="submit">并将其移动onclick="..."到 a onsubmit="..."。这不需要太多容易出错的 JavaScript,并且可以在更多情况下工作。

于 2009-10-26T19:05:31.443 回答