【问题标题】:Detect if a specific textbox has focus [duplicate]检测特定文本框是否有焦点[重复]
【发布时间】:2013-12-03 10:25:44
【问题描述】:

我首先要说的是,自从我上次编写 Greasemonkey/Userscripts 以来已经有几年了,我的 JavaScript 有点生疏了,这应该是一个简单的问题。

我正在尝试检测特定文本框是否具有焦点。 (我计划在特定框具有焦点并且用户按下回车键时运行脚本。)我的问题是该站点没有文本框的 ID 标签,只有名称标签 <input type="text" size="20" value="" name="Category_Product_Search"></input> 和几乎所有我看到的教程要求文本框有一个 ID 标签。

谢谢,

查尔斯

【问题讨论】:

    标签: javascript forms greasemonkey userscripts


    【解决方案1】:

    您可以简单地在其 focus 事件上测试焦点元素,但我建议绑定到一个更接近的祖先元素,其中包含您要测试的 所有 元素,而不是body我将在我的演示代码中使用:

    function elementIs (e){
        var target = e.target,
            targetTagName = target.tagName.toLowerCase();
        /* Using a switch () rather than if/else if/else, for simplicity and
           ease of extension to other focusable element-types, though adjust
           to whichever technique you're more comfortable with:
        */
        switch (targetTagName){
            case 'input':
                if (target.name === 'Category_Product_Search') {
                    // do something, it's an input and has the right name:
                }
        }
    }
    document.body.addEventListener('focus', elementIs, true);
    

    JS Fiddle demo.

    参考资料:

    【讨论】:

      【解决方案2】:

      如果输入框的顺序是固定的,可以使用form = document.getElementsByTagName('input')。然后您可以简单地使用所需文本框的索引号。

      如果名称标签是唯一的,那么你也可以在之后使用 form.elements["name"]。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-14
        • 2011-10-06
        • 2013-12-20
        • 1970-01-01
        • 2011-09-18
        相关资源
        最近更新 更多