在下面的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 :(得分:0)
我相信你想要的代码看起来更像这样。代码是自我评论的
/*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>
&#13;