简体   繁体   中英

Variable passed into function not working JavaScript

I am trying to create two functions that will allow me to scroll through an array of image sources and display them in my image view: a nextImage() and a previousImage() one. These work if I use the original num variable but if I try to make it more general so I can reuse them in my code and I pass in the variable num as a parameter in my window.onload it does not work, It just reaches number 1 and does not go backwards. Please look at the code. Thank you in advance, Alessandro

var num = 0;

var imagesArray1 = ["img/campionatigiovanili2018/img1.jpg", "img/campionatigiovanili2018/img2.jpg", "img/campionatigiovanili2018/img3.jpg"];

window.onload = function(){
  let logo = document.getElementById('logo');
  logo.addEventListener("click", function(){
    window.location.href = "index.html";
  });



  document.getElementById('postImage1').setAttribute("src", imagesArray1[num]);


  //previous image
  document.getElementById('previousImage').addEventListener("click", function(){
    previousImage("postImage1", imagesArray1, num)
});

document.getElementById('nextImage').addEventListener("click", function(){
  nextImage("postImage1", imagesArray1, num);
});

};

function nextImage(postImage, imageArray, myVar){
  if (myVar < 2) {
    myVar = myVar+1
    document.getElementById(postImage).setAttribute("src", imageArray[myVar]);
    console.log(myVar);
  } else {
  }
};

function previousImage(postImage, imageArray, myVar){
  if (myVar > 0) {
    myVar = myVar-1
    document.getElementById(postImage).setAttribute("src", imageArray[myVar]);
    console.log(myVar);
  } else {
  };
}

Please access num variable inside the function, and not pass it as parameter:

function nextImage(postImage, imageArray){
  if (num < 2) {
    num = num +1
    document.getElementById(postImage).setAttribute("src", imageArray[num]);
    console.log(num);
  } else {
  }
};

As myVar and num in this case are two different variables.

Javascript always pass parameters by value if they're primitive ( like your num variable)

The solution is:

  • Simply directly edit num inside event handler, since it's a global variable.

  • Declare it as an object: var currentObj = { num:0};

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM