javascript 在 Safari 中防止默认

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6185992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 19:48:24  来源:igfitidea点击:

preventDefault in Safari

javascriptjqueryhtmlsafariwebkit

提问by testndtv

I have a textbox which has the code;

我有一个包含代码的文本框;

<input type="text" maxlength="5" size="2" value="1" id="paging_textbox">

Now there is no encloding form tag on this page..

现在这个页面上没有包含表单标签..

When user types in this textbox and presses Enter, the table on this page is updated (via AJAX call)

当用户在此文本框中键入并按 Enter 时,此页面上的表格会更新(通过 AJAX 调用)

In Safari, the behavior is slightly different in the sense that even though it updates the table correctly, it kind of reloads the page (think it submits the form, but not sure how as there is no form tag) and resets the textbox value back to "1"

在 Safari 中,行为略有不同,即使它正确更新了表格,它也会重新加载页面(认为它提交了表单,但不确定如何,因为没有表单标签)并将文本框值重置回来到“1”

How do I prevent this from happening in Safari ?

如何防止这种情况在 Safari 中发生?

Please help me. Thank you.

请帮我。谢谢你。

回答by tXK

Just to be sure, terminate your callback function with a return false. That should do the trick.

可以肯定的是,使用return false. 这应该够了吧。

 function(e) {
     e.preventDefault();
     // some awesome code
     return false;
 }

Oh, and another thing: in the future, to avoid such random behavior.. respect the standards, use a form:)

哦,还有一件事:将来,为了避免这种随机行为..尊重标准,请使用form:)

回答by diEcho

in jQuery

在 jQuery 中

//Press Enter in INPUT moves cursor to next INPUT
$('#form').find(':input').keypress(function(e){
    if ( e.which == 13 )
    {
        $(this).next().focus();  //Use whatever selector necessary to focus the 'next' input
    }
});

JAVASCRIPT

爪哇脚本

<script language="JavaScript">
function disableEnterKey(e)
{
     var key;
     if(window.event)
          key = window.event.keyCode;     //IE
     else
          key = e.which;     //firefox
     if(key == 13)
          return false;
     else
          return true;
}
</script>

and write

和写

<input type=”text” name=”mytext” onKeyPress=”return disableEnterKey(event)”>

回答by Abdul Kader

use event.preventDefault()or return False should do the trick for you.

使用event.preventDefault()或返回 False 应该为您解决问题。