.focus()在这种情况下不起作用?

时间:2013-10-23 22:06:30

标签: javascript jquery this

此代码应在每个锚点,按钮和输入元素旁边创建少量编号的标记。然后,它会在这些标记上设置点击事件。我已经删除了按钮和锚标签的代码,因为它有效且不相关。

但是,对于输入,应该发生的是光标应该放在input元素中,使用.focus()方法实现。

但是当我在控制台中对着登录的gmail.com运行它时,它什么也没做。无论这意味着什么,评论alert()语句都将返回[Object HTMLSpanElement]。如果我取消注释document.getElementById行以直接关注搜索栏 ,则可行。为什么不能使用this

我正在使用gmail仅用于测试示例,但这种行为是在所有页面上,错误始终存在。您可以使用this在控制台中包含jQuery来测试它。

var n = 1;
$('a,button,input').each(function(){
                        id = n;
                   //creates numbered tags next to 'a', 'button' and 'input' elements
                        var a = $(this).offset();
                        $('body').append('<span class="numTag" id="' + id + '" style="background:white; border: 1px solid black; font-size: 10pt; position:absolute; z-index:999;">' + id + '</span>');
                        $('#'+id).css({left: a.left - 25, top: a.top});
                        switch( this.tagName)
                        {
                        case 'A':
                            break;
                        case 'BUTTON':
                            break;
                        case 'INPUT':
                            $('#'+id).click(function(){
                                //alert(this);
                                this.focus();
                                //document.getElementById('gbqfq').focus();
                            });
                            break;
                        }
                        n++;
                    }
                });

1 个答案:

答案 0 :(得分:2)

您在点击事件中失去了对this的访问权限。存储对它的引用,以便以后可以访问它。

var self = this;
$('#'+id).click(function(){
    //alert(self);
    self.focus();
    //document.getElementById('gbqfq').focus();
});