【问题标题】:jQuery plugin scope of settings passed in传入的 jQuery 插件设置范围
【发布时间】:2009-10-04 23:02:34
【问题描述】:

我觉得肯定有人问过这个问题,但我无法通过搜索找到它。

这是一个让我困惑的问题的完整示例:

<html><head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
(function($){
    $.fn.testPlugin = function(options){
    settings = $.extend({val : "default"}, options);
    return this.each(function(){
        $(this).click(function(e){ 
        e.preventDefault();
        console.log(settings.val);
        });
    });
    }
 })(jQuery);

$(document).ready(function(){
    $('a#a1').testPlugin();
    $('a#a2').testPlugin({val : 'new val'});

});
</script>
</head><body>
<a href="#" id="a1">A1</a>
<a href="#" id="a2">A2</a>
</body>
</html>

单击任一链接都会将“new val”记录到您的 firebug 控制台。您可能会想像我希望第一个链接保留默认设置,而第二个链接保留我的设置。插件必须有一个标准模式来实现这一点?

【问题讨论】:

    标签: javascript jquery function scope arguments


    【解决方案1】:

    我认为您需要使用varsettings 变量保持在范围内。试试:

     $.fn.testPlugin = function(options){
            var settings = $.extend({val : "default"}, options);
            return this.each(function(){
                $(this).click(function(e){ 
                    e.preventDefault();
                    console.log(settings.val);
                });
            });
        }
    

    【讨论】:

    • 已更新 - 我想我对 $.extend 参数顺序感到困惑。
    猜你喜欢
    • 2011-11-02
    • 2011-12-13
    • 1970-01-01
    • 2021-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多