我创建了以下功能。
function showAllSelectOpts(select)
{
selectLength = select.children().length;
select.attr('size',selectLength);
select.css('height','auto');
select.focusout(function(){
select.attr('size','1');
});
}
当在这样的select元素上直接调用showAllSelectOpts(mySelect);
它时,它可以正常工作,但是在另一个函数中(如下所述)使用关键字“ this”调用时,它将返回错误。类型错误:select.children不是函数
$('select').on('focus',function(){
showAllSelectOpts(this);
})
这是范围问题还是什么,我该如何解决?
在事件处理程序中,this
是对DOM元素的引用,而不是jQuery对象。但是您showAllSelectOpts
希望它的参数是jQuery对象。
更改调用以将DOM元素包装为$()
:
showAllSelectOpts($(this));
...或showAllSelectOpts
自行更新:
function showAllSelectOpts(select)
{
select = $(select); // ***
selectLength = select.children().length;
select.attr('size',selectLength);
select.css('height','auto');
select.focusout(function(){
select.attr('size','1');
});
}
旁注:正如A.Wolff指出的那样,函数在每次调用时都会将新的 focusout
处理程序附加到select上。你只想要一个。
我将完全删除处理程序的这一部分,并用一个替换它focusout
:
function showAllSelectOpts(select)
{
var selectLength = select.children().length;
select.attr('size',selectLength);
select.css('height','auto');
}
$('select')
.on('focus',function(){
showAllSelectOpts($(this));
})
.on('focusout', function(){
$(this).attr('size', '1');
});
另外请注意,我添加了一个var
用于selectLength
在showAllSelectOpts
(尽管实际上,你可以只取出完全可变); 没有一个,该代码就成为“隐含全球性恐怖”的 牺牲品(这是我贫乏的小博客上的一篇文章)。确保声明您的变量。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句