jQuery阻止仅在输入时提交 [英] Jquery prevent ONLY submit on enter

查看:109
本文介绍了jQuery阻止仅在输入时提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么此代码在注释了警告行的情况下起作用,而在未注释时却不起作用?

我想阻止表单提交,但是在enter上允许其他功能(例如,在其他页面中执行$ .get()).对不起,我的英语不好.

$(document).ready(function() {
    $('#txtPesquisaServidor').keydown(function(event){
        if(event.keyCode == 13) {
            //alert('enter!');
            event.preventDefault();
            return false;
        }
    });
});

我正在使用Jquery 1.6.2.

完成!问题是alert https://jsfiddle.net/o0mkjnwk/1/

解决方案

而不是使用.keydown()方法,请尝试使用.on('keypress', function...

有关工作示例,请参见以下小提琴: http://jsfiddle.net/p1agoka1/

我看到您正在使用jQuery 1.6.2. .on()事件处理程序至少需要1.7.0.您为什么要使用这样的旧版本?

如果您还有其他较旧版本的代码无法与jQuery的较新版本一起使用,则可以尝试实现jQuery Migrate,以重新启用最新版本中不存在的jQuery的某些较旧功能. https://github.com/jquery/jquery-migrate/

Why this code works with the alert line commented, but dont work when not commented?

I want block the form submit, but allow other functions on enter (example, do $.get() in other page). Sorry for my bad english.

$(document).ready(function() {
    $('#txtPesquisaServidor').keydown(function(event){
        if(event.keyCode == 13) {
            //alert('enter!');
            event.preventDefault();
            return false;
        }
    });
});

I'm using Jquery 1.6.2.

EDIT: Done! The problem was the alert https://jsfiddle.net/o0mkjnwk/1/

解决方案

Instead of using the .keydown() method, try using .on('keypress', function...

See the following fiddle for a working example: http://jsfiddle.net/p1agoka1/

EDIT: I see you're using jQuery 1.6.2. The .on() event handler requires at least 1.7.0. Is there any reason why you're using such an old version?

If you have some other older code that does not work with a newer version of jQuery, you could try to implement jQuery Migrate which re-enables some older features of jQuery not present in up-to-date versions. https://github.com/jquery/jquery-migrate/

这篇关于jQuery阻止仅在输入时提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆