[英]jQuery plugin scope of settings passed in
我覺得必須要問這個問題,但是我無法通過搜索找到它。
這是使我感到困惑的問題的完整示例:
<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控制台。 您可能會想到,我希望第一個鏈接保留默認設置,而第二個鏈接保留我的覆蓋設置。 必須為插件實現此標准的模式嗎?
我認為您需要使用var
將settings
變量保留在范圍內。 嘗試:
$.fn.testPlugin = function(options){
var settings = $.extend({val : "default"}, options);
return this.each(function(){
$(this).click(function(e){
e.preventDefault();
console.log(settings.val);
});
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.