javascript - 为什么 jquery 插件函数总是返回对象而不是字符串?

标签 javascript jquery jquery-plugins

这是我的自定义 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") )

我想不通的是为什么返回链不起作用?

最佳答案

因为each的返回值就是你调用each的对象。函数each calls的返回值用于判断是否停止循环(即迭代函数可以返回false停止循环— docs link )。

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

如果您的意思是通过您的插件将 myVal 存储在 jQuery 实例上:

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从中获取原始数组。

关于javascript - 为什么 jquery 插件函数总是返回对象而不是字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8821537/

相关文章:

javascript - Jquery $(this).val();上 .ready 不工作

javascript - 如何使用 html/css 使链接看起来像标签?

JavaScript 数组填充

php - JQuery $.post 错误

jQuery 无缝轮播

javascript - 具有自动高度的 iframe

jQuery 插件外部函数

javascript - 为什么较新版本的 Node 不从请求正文中删除 __proto__ ?

javascript - 使用 js 或 jquery 单击工具栏按钮后包裹 html 标签

javascript - 固定标题表在水平滚动时出现问题