2015-03-03 24 views
0

function changing()下面我試圖獲取數組arr [0]的值並輸出一些與數組值有關的信息。我想問題是arr沒有被更新。我需要更新這個事件之外的數組,以便我可以使用函數中的值。我怎樣才能做到這一點?林學習的pub/sub和.trigger(),所以如果你可以給屬於該風格的結果,將是巨大嘗試獲取事件外的更新數組的值

arr = [] 
$('body').on("clicked", function() { 
    // $(".clickMe").on("click", function(){ 
    if ($('#thisBox')[0].checked) { 
     $('#thisBox').prop('checked', false); 
     data = false; 
     console.log(data) 
     arr[0] = (data) 
     console.log(arr) 
    } else { 
     $('#thisBox').prop('checked', true); 
     // console.log(prop('checked')) 
     data = true; 
     console.log(data) 
     arr[0] = data 
     console.log(arr) 
    } 
    // }); 
}); 
console.log("outside" + arr) 

function changing() { 
    $('body').trigger("clicked"); 
    if (arr[0] == undefined) { 
     $(".output").html("set undefined") 
    } else if (arr[0] == true) { 
     $(".output").html("set true") 
    } else if (arr[0] == false) { 
     $(".output").html("set false") 
    } 
} 
changing() 

$(".secondClick").on("click", function() { 
    $('body').trigger("clicked"); 
    if (arr[0] == true) { 
     $("body").css("backgroundColor", 'blue') 
    } else if (arr[0] == false) { 
     $("body").css("backgroundColor", 'green') 
    } 
}) 
+0

什麼#thisBox ???也許你可以做一個小提琴:http://jsfiddle.net所以你可以幫助你更好。 – Fourat 2015-03-03 13:44:46

+0

http://jsfiddle.net/qnounnj2/ – 2015-03-03 13:49:28

+2

@詹姆斯你在哪裏看到異步調用? – 2015-03-03 13:49:49

回答

0

我相信你想要的代碼看起來更象這樣。該代碼是自我評價

JSFiddle

/*Click handles change colors button*/ 
 
$('.secondClick').click(function() { 
 
    /*sets checked to a boolean of the checkbox*/ 
 
    var checked = $('#thisBox').prop('checked'); 
 
    /*executes function*/ 
 
    change(checked); 
 
}); 
 
/*Handles alternate colors button*/ 
 
$('.alternateClick').click(function() { 
 
    /*Sets the checkbox opposite of what the checkbox was*/ 
 
    $('#thisBox').prop('checked',!$('#thisBox').prop('checked')); 
 
    /*sets checked to a boolean of the checkbox*/ 
 
    var checked = $('#thisBox').prop('checked'); 
 
    /*executes function*/ 
 
    change(checked); 
 
}); 
 

 
/*takes a boolean to change body color*/ 
 
function change(myBoolean) { 
 
    if (myBoolean) { 
 
     $("body").css("backgroundColor", 'blue'); 
 
    } else { 
 
     $("body").css("backgroundColor", 'green') 
 
    } 
 
} 
 
/*initiates the first change events so the page 
 
is green on first page run.*/ 
 
change($('#thisBox').prop('checked'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input id="thisBox" type="checkbox"></input> 
 
<button class="secondClick">Change Colors</button> 
 
<button class="alternateClick">Alternate Colors</button>

+0

感謝您的答覆。這是不使用數組的做法,但我試圖學習如何在事件之後更新數組,並在整個項目中使用數組值,就像我在我的問題中代碼中所做的那樣。我開始認爲這是不可能的,我必須改變我的想法,但我真的認爲這是可能的。通過bub子可能使用.trigger()和.on()但每次我嘗試做它我卡住了。 – 2015-03-03 14:19:24