2012-01-11 110 views
3

这里是我的自定义jQuery插件代码:为什么jquery插件函数总是返回对象而不是字符串?

(function($){ 
    $.fn.extend({ 
     getmyValue : function(){ 
     return this.each(function() { 
       return this.myVal; 
     }); 
     }, 
     initPlugin : function(){ 
     return this.each(function() { 
       this.myVal='Some results'; 
     }); 
     } 
    }); 
})(jQuery); 

当我运行这段代码:

$(document).ready(function() { 

$("#div").initPlugin(); 
alert($("#div").getmyValue()); 
}); 

返回的值不是像预想的那样一个普通的字符串,但一个对象($(“# div“)返回)

我弄不明白为什么返回链接不工作?

+1

你回来的'this.each'的结果,这不是一个字符串。你为什么不返回'this.myVal'?目前还不清楚你想要完成什么。 – 2012-01-11 15:10:43

回答

4

因为each的返回值是您称为each的对象。函数返回值each调用用于确定是否停止循环(也就是说,迭代函数可以返回false来停止循环。)  — docs link)。

从代码中不清楚你真的想在getmyValue中做什么;返回你存储在jQuery实例本身的值?返回存储在第一个包含元素上的myVal?从所有包含的元素中返回myVal值的数组?

如果你的意思是你的插件存储在jQuery的实例myVal

getmyValue : function(){ 
    // Here, `this` is the jQuery instance on which `getmyvalue` was called 
    return this.myVal; 
}, 

如果你的第一个元素意味着myVal(注意,这是在典型情况下,原始DOM元素):

getmyValue : function(){ 
    // Here, `this` is the jQuery instance on which `getmyvalue` was called. 
    // `this[0]` is the first matched element (a raw DOM element, typically). 
    // Note we check before accessing it to see if it's there, since a jQuery 
    // instance may have matched zero elements. 
    return this[0] ? this[0].myVal : undefined; 
}, 

如果指由所有匹配的元素的myVal值的阵列(再次,这些将在典型的情况下,原料的DOM元素):

getmyValue : function(){ 
    // Here, `this` is the jQuery instance on which `getmyvalue` was called. 
    return this.map(function() { 
      // Here, though, `this` one of the elements wrapped by the jQuery, 
      // instance typically a raw DOM element. (Each of them in a loop.) 
      return this.myVal; 
    }).get(); 
}, 

...它使用map来获取jQuery包装的值的数组,然后get从它得到原始数组。

+0

感谢这就是我一直在寻找:) – mrbm 2012-01-11 15:21:38

0

返回.each是一个对象。如果用.map替换它,则代码将返回逗号分隔的值列表。

jQuery Map

+0

*“如果你用.map替换它,那么你的代码将返回一个以逗号分隔的值列表。”*不,它会返回一个包装值的jQuery实例。根据你链接的文档。 – 2012-01-11 15:20:11

+0

我错过了'.get()。join(',');'。这将采取返回值并正确格式化。 – kwelch 2012-01-11 15:24:02

1

你返回的this.each()的结果,而不是this.myVal

getmyValue: function() { 
    return this.myVal; 
} 
相关问题