我创建了一个名为showMoreImages的函数,它接受状态作为参数来检查它是否为真,然后将其值与其他一些操作一起更改为false。但是当我尝试它时不会更新引用的布尔值。在代码段下面。
function showMoreImages(num, el, category, state){
for (var i = 0; i < category.length; i++) {
toggleClass('show-images', category[i]);
toggleClass('hide-images', category[i]);
}
if(state) {
updateState('shift-down', 'shift-up', image_one[num]);
el.innerHTML='View Less';
state=false;
}else{
updateState('shift-up', 'shift-down', image_one[num]);
el.innerHTML='View More';
state=true;
}
}
调用函数的地方:
if (i==1) {
var isPlacesClose=true;
buttons[i].addEventListener('click', function(){
showMoreImages(0, this, places, isPlacesClose);
});
}
if (i==2) {
var isPeopleClose=true;
buttons[i].addEventListener('click', function(){
showMoreImages(1, this, people, isPeopleClose);
});
}
if (i==3) {
var isEventsClose=true;
buttons[i].addEventListener('click', function(){
showMoreImages(2, this, events, isEventsClose);
});
}
我想要实现的是更新作为参数传递的布尔值。例如,在i = 1的情况下,我想将isPlacesClose更新为false,反之亦然。
提前致谢!
答案 0 :(得分:0)
state
是原始值,当其值在showMoreImages
中更改时,不会保留在showMoreImages
范围之外
返回值
function showMoreImages(num, el, category, state){
for (var i = 0; i < category.length; i++) {
toggleClass('show-images', category[i]);
toggleClass('hide-images', category[i]);
}
if(state) {
updateState('shift-down', 'shift-up', image_one[num]);
el.innerHTML='View Less';
return false; //observe change in this line, value is returned instead of setting the same in state
}else{
updateState('shift-up', 'shift-down', image_one[num]);
el.innerHTML='View More';
return true; //observe change in this line, value is returned instead of setting the same in state
}
}
现在接收在参数
中传递的变量中的返回值if (i==1) {
var isPlacesClose=true;
buttons[i].addEventListener('click', function(){
//observe change in this line, isPlacesClose is updated with returned value
isPlacesClose = showMoreImages(0, this, places, isPlacesClose);
});
}
if (i==2) {
var isPeopleClose=true;
//observe change in this line, isPeopleClose is updated with returned value
buttons[i].addEventListener('click', function(){
isPeopleClose = showMoreImages(1, this, people, isPeopleClose);
});
}
if (i==3) {
var isEventsClose=true;
buttons[i].addEventListener('click', function(){
isEventsClose = showMoreImages(2, this, events, isEventsClose);
});
}