[英]Javascript function “return this” not working
我有以下功能,它仅遍历对象列表并返回正确的对象:
function findLine(textElement,caretIndex){
jQuery.each(textElement.lines(), function() {
if(this.startIndex <= caretIndex && this.endIndex >= caretIndex) {
alert(this);
return this;
}
});
}
当我用它调用它时,我得到的是undefined
的回报。
line = findLine(textElement,caretIndex);
alert(line);
当我运行line = findLine(textElement,caretIndex);
时,这很奇怪 该函数内的警报将被触发并返回正确的结果。 因此, this
是正确的值,但是当触发函数外部的第二个警报时,我将得到undefined
。
当我从函数返回值时发生了某种错误,或者与将该值分配给变量有关。 我在这里做错了什么?
问题是您return this
是在jQuery.each
方法的回调中,而findLine
不返回任何内容。
function findLine(textElement,caretIndex){
return jQuery.each(textElement.lines(), function() {
if(this.startIndex <= caretIndex && this.endIndex >= caretIndex) {
alert(this);
return this;
}
});
}
如果return
的jQuery.each
叫你将与一个包含每个jQuery对象最终this
是你想要。
从.each()的jQuery文档中:
通过使回调函数返回false,可以在特定的迭代中破坏$ .each()循环。 返回非false与for循环中的continue语句相同; 它将立即跳至下一个迭代。
因此,您的return this
语句本质上是一个continue
语句,因为this
不是错误的。 将函数更改为此可能会起作用(未经测试...并且可能比.each()使用更好的函数,例如.filter()或.grep()):
function findLine(textElement,caretIndex){
var result;
jQuery.each(textElement.lines(), function() {
if(this.startIndex <= caretIndex && this.endIndex >= caretIndex) {
alert(this);
result = this;
return false; // returning false in the callback just causes the loop to exit
}
});
return result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.