I'm trying to build a vanilla js carousel. I want to incrementally increase or decrease a variable onClick, but I'm getting an Undefined issue. If I embed the the code in the HTML file everything works fine, when I move it to an external js file, I get an Undefined error. I feel like I'm missing some sort of information about scope.
let i = 0;
function carouselControl() {
console.log(i);
}
<div class="container">
<div class="carousel">
<a onclick="carouselControl(i--);">
<div class="carousel__control"><img src="https://upload.wikimedia.org/wikipedia/commons/0/0d/Caret_left_font_awesome.svg"></a>
</div>
<div class="carousel__img"><img src="https://picsum.photos/1125/750"></div>
<div class="carousel__img hidden"><img src="https://picsum.photos/1126/750"></div>
<div class="carousel__img hidden"><img src="https://picsum.photos/1127/750"></div>
<a onclick="carouselControl(i++);">
<div class="carousel__control"><img src="https://upload.wikimedia.org/wikipedia/commons/d/de/Caret_right_font_awesome.svg"></a>
</div>
</div>
</div>
答案 0 :(得分:0)
Your carouselControl
function is not expecting any parameters (the parenthesis part).
When you call your function in the HTML onclick
, you are passing the actual code in the parameters part.
Change your function to something like:
function carouselControl(operation){
if (operation == "increase") i++;
if (operation == "decrease") i--;
}
And in your HTML do:
<a onclick="carouselControl("decrease");"><div class="carousel__control"><img src="../img/symbols/left.svg"></a></div>
<a onclick="carouselControl("increase");"><div class="carousel__control"><img src="../img/symbols/right.svg"></a></div>
答案 1 :(得分:0)
You are trying to send a variable that is unknown in the first file, also you did not define that the carouselControl()
will receive any variables with the function call. What you can do is :
let i = 0;
function carouselControl(condition) {
if(condition == 1) // increasing the "i" value
i++;
else if ( condition == 0) // decreasing the "i" value
i--;
console.log(i);
}
and at the first file you would just have to change the carouselControl(i--)
to carouselControl(1)
for the button that you want to increase the number and carouselControl(0)
for the button that you want to decrease the number.