2013-11-03 58 views
2

我試圖將numbers設置爲與digits相等。 我該怎麼做?我試過'numbers' : digits但它不起作用。使用變量外部函數

// Checks if the checkbox is checked or not 
$('#digits').change(
    function(){ 
    if ($(this).is(':checked')) { 
     digits = true; 
    } else { 
     digits = false; 
    } 
}); 

// When the button "apply" is pressed it sets numbers equal to digits and calls the function test 
$(document).ready(function(){  
    $('#apply').test({ 
     'numbers': digits // This is where I'm stuck 
    }); 
}); 

(function($){ 
    var methods = { 
    init : function(options, callbacks) { 
     var settings = $.extend({ 
     'numbers': true, 
    }, options); 
    ... 
    ... 
    ... 
    etc 
    $.fn.test= function(method) { 
     alert("SUCCESS"); 
     ... 
     ...  
    }; 
})(jQuery); 

Working Example (JSFIDDLE)

+1

您的'.test()'調用只發生一次,當DOM第一次加載時,它將使用當時的數字值。當'.change()'處理程序運行時,它不會對先前完成的任何操作產生任何影響。 – Barmar

回答

2

當你初始化你的插件,你給它在這個階段的digits值。從你發佈的代碼中,我猜想它是undefined。每次通過複選框更改插件時,都需要更新插件上的值。

一個快速解決方法是將初始化插件的代碼移動到複選框的change處理程序,不過也可以考慮初始化插件一次並實現setter方法以允許您在插件之後更新插件的值它已被初始化。

// Checks if the checkbox is checked or not 
    $('#digits').change(
     function(){ 

     $('#apply').test({ 
      'numbers': this.checked 
     }); 
    }); 
+0

如果我有多個複選框和多個變量會怎麼樣? – kalpetros

+0

你可以嘗試在你的問題中清楚你想要達到的目標嗎?我盡力用你提供的信息做到最好,但就目前而言,這些都有點抽象 - 至少對我來說。 –

+0

我添加了一個JSFIDDLE鏈接,顯示了我想要做的事情。每次點擊應用程序時,我都希望我的代碼能夠讀取複選框是否被選中。 – kalpetros