Javascript函数"return this"不工作

Javascript function "return this" not working

本文关键字:quot 工作 this return Javascript 函数      更新时间:2023-09-26

我有以下函数,它只是遍历对象列表并返回正确的对象:

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;
        }
   });
}

如果你returnjQuery.each调用,你将结束与一个jQuery对象,其中包含每个this,你想要的

来自jQuery文档中的。each():

可以通过使回调函数返回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;
}