简体   繁体   English

传递给函数的变量无法使用JavaScript

[英]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. 我正在尝试创建两个函数,这些函数将允许我滚动浏览图像源数组并在图像视图中显示它们:nextImage()和previousImage()一个。 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. 如果我使用原始的num变量,但可以正常工作,但是如果我尝试使其更通用,以便可以在代码中重用它们,则我将num变量作为参数传递给我的window.onload它不起作用,它只能达到number 1,并且不会向后退。 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: 请在函数内部访问num变量,不要将其作为参数传递:

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. 由于myVarnum在这种情况下是两个不同的变量。

Javascript always pass parameters by value if they're primitive ( like your num variable) 如果参数是原始参数,则Javascript总是按值传递参数(例如num变量)

The solution is: 解决方案是:

  • Simply directly edit num inside event handler, since it's a global variable. 由于它是全局变量,因此可以直接在事件处理程序中直接编辑num

  • Declare it as an object: var currentObj = { num:0}; 将其声明为对象: var currentObj = { num:0};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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