2012-01-11 107 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; 
} 
相關問題