How I call the function:
function createHTML(){
...
monthDiv.setAttribute('onclick', 'onOptionSelected(`' + monthDiv.id + '`)');
....
}
-numSelected is the times that a div can be selected.
function onOptionSelected(option) {
if(numSelected <= 2){
numSelected ++;
console.log("NUMSELECTEED: " + numSelected);
selectedMonths.push(option);
if ($('#' + option + '').hasClass("unSelected")) {
$('#' + option + '').removeClass("unSelected").addClass("selected");
} else if ($('#' + option + '').hasClass("selected")) {
$('#' + option + '').removeClass("selected").addClass("unSelected");
}
}
}
After you select 3 divs, nothing happens, the "onclick" doesn't work.
Actually, after you click 3 times in any box, two times the same box, doesn't matter, after 3 clicks, doesnt work.
you're creating multiple divs (i assume in some sort of for loop).
Delete the "numSelected" global variable declaration you have, and try something like this:
var aNumSelected[];
function createHTML(){
...
monthDiv.setAttribute('onclick', 'onOptionSelected(`' + monthDiv.id + '`)');
aNumSelected.push({ id : monthDiv.id, numSelected : 0 });
....
}
function onOptionSelected(option) {
var numSelected;
var i;
for (i = 0; i < aNumSelected.length(); i++){
if (aNumSelected[i].id == option){
numSelected = aNumSelected[i].numSelected;
break;
}
}
if(numSelected <= 2){
numSelected ++;
console.log("NUMSELECTEED: " + numSelected);
selectedMonths.push(option);
if ($('#' + option + '').hasClass("unSelected")) {
$('#' + option + '').removeClass("unSelected").addClass("selected");
} else if ($('#' + option + '').hasClass("selected")) {
$('#' + option + '').removeClass("selected").addClass("unSelected");
}
aNumSelected[i] = { id: option, numSelected: numSelected };
}
}
numselected seems to be a global variable and therefore is shared by all divs.
You have to store a dedicated value for each div.
Your variable numSelected
is most likely never being reset and is in a higher scope than you think. You increment it in this but it's the same value for all buttons. So on that third click, no matter the button pressed, if(numSelected <= 2){
fails.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.