javascript - 如何不失去对登录页面的关注

标签 javascript jquery html forms focus

我有一个简单的登录表单,其中包含 2 个输入字段:“用户名”和“密码”。 “用户名”字段默认聚焦。问题是,当用户在“用户名”或“密码”字段外单击时,焦点消失了(它既不在“用户名”上,也不在“密码”字段上)。我如何强制将焦点放在这两个字段上只有?

就我而言,这是一个非常烦人的行为,所以我真的很想这样做:)

我可以做类似的事情吗:

$("*").focus(function() {
    if (!$(this).hasClass("my_inputs_class")) {
        // How to stop the focusing process here ?
    }
});

?

最佳答案

听起来您总是希望您的输入之一是有焦点的,这很公平。我这样做的方法是绑定(bind)您的每个输入 blur() 事件,这样如果它发生,它就会转到下一个元素。

这是标记:

<body>
<form method="POST" action=".">
    <input type="text" name="username" />
    <input type="password" name="password" />
    <input type="submit" name="submit" />
</form>
</body>

这是 jQuery:

$(document).ready(function() {
    // what are the named fields the user may focus on?
    var allowed = ['username', 'password', 'submit'];
    $.each(allowed, function(i, val) {
        var next = (i + 1) % allowed.length;
        $('input[name='+val+']').bind('blur', function(){
            $('input[name='+allowed[next]+']').focus();
        });
    });
    $('input[name='+allowed[0]+']').focus();
});

关于javascript - 如何不失去对登录页面的关注,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3015199/

相关文章:

jquery - 如何集成visual composer自定义wordpress主题

javascript - jQuery MultiSelect 插件 SumoSelect 未绑定(bind)到单个页面上的多个实例

html - 将一个类添加到现有的类包中

javascript - 如何解决“未定义的错误 "Uncaught TypeError: Cannot call method 'changePage”

javascript - UILayout 的可变范围

javascript - 在 redux 中复制大状态不会降低性能吗?

javascript - 将字符串传递到 Onchange

java - Angularjs UI Bootstrap Popover 阻止输入提交

javascript - for 循环中的数组(使用 jQuery)

html - 如何制作像 Google Doodle 的神秘博士这样的 HTML5 游戏?