【问题标题】:jQuery set focusjQuery设置焦点
【发布时间】:2014-12-26 23:11:36
【问题描述】:

如何在 jQuery 中设置焦点?在 focusout 事件中,我一直试图将注意力集中在控件上,但它似乎不起作用。

$(function() {
    $("#Line1").focusout(function() {
        alert("YOU CAN'T LEAVE HERE");
        $("#Line1").focus();
    });
});

我的特定应用程序在离开焦点时尝试验证字段,如果验证失败,我希望焦点保持在该控件上。

Here is my code on jsfiddle.net

【问题讨论】:

    标签: jquery focus


    【解决方案1】:

    jsFiddle

    在谷歌浏览器中,上面的例子是有效的

    HTML

    <table id="bz_eventtable" border="" cellspacing="1" cellpadding="2">
        <tbody>
            <tr>
                <td class="bzHeading">Line 1:</td>
                <td class="bzDataTT">
                    <input id="Line1" value="" maxlength="50" size="50" name="Line1"/>
                </td>
            </tr>
            <tr id="errorLine1">
                <td colspan="2">
                    <span>Error in Line 1</span>
                </td>
            </tr>
            <tr>
                <td class="bzHeading">Line 2:</td>
                <td class="bzDataTT">
                    <input id="Line2" value="" maxlength="50" size="50" name="Line2"/>
                </td>
            </tr>
        </tbody>
    </table>
    

    JS

    $(function() {
        $("#errorLine1").hide();
        $("#Line1").focusout(function() {
            $("#errorLine1").show().delay(3000).fadeOut();
            $("#Line1").focus();
        });
    });
    

    CSS

    body {
        font-family:Tahoma;
        font-size : 8pt;
        padding-left:10px;
    }
    input[type="text"] {
        font-family:Tahoma;
        font-size : 8pt;
        width:150px;
    }
    

    【讨论】:

      【解决方案2】:

      您不能在focusout 事件中更改焦点,因为浏览器已经在更改焦点。浏览器完成更改焦点后,您可以使用计时器将焦点更改回来:

      $(function() {
        $("#Line1").focusout(function() {
          alert("YOU CAN'T LEAVE HERE");
          window.setTimeout(function(){
            $("#Line1").focus();
          }, 0);
        });
      });
      

      演示:http://jsfiddle.net/Guffa/12j5jraa/6/

      注意:您应该真正考虑是否有任何其他方式可以完成您想要完成的任何事情。不允许用户离开字段的行为可能非常烦人!

      【讨论】:

        猜你喜欢
        • 2011-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-14
        相关资源
        最近更新 更多