The javascript (jQuery) variable returns multiple values. It is added, not constantly overwritten.

Asked 2 years ago, Updated 2 years ago, 54 views

var i;
function slide(i){
       //$previewImg Click to receive and use variable i
        console.log(i);
};

$previewImg.on('click', function(){
        i = $previewImg.index(this);
        slide(i);
});

Each time $previewImg is clicked, the variable i is added to the variable with a new i value when clicked instead of a single value. I wonder how to overwrite with the last added variable in the slide function. ㅠ < I thought I could solve it with vari = i but it doesn't work.

If you check with console.log(i), a new value is printed on the second line of the value of the previous variable i, but I want to print only the new value!

javascript jquery variable

2022-09-21 16:04

1 Answers

I saw the full source you uploaded... i cannot be changed.

function slide(i){
  /* Blah blah blah... */
  if (!$previewImg.hasClass('active')) {
    $previewImg.children('img').mouseover(function(){
      $(this).addClass('active');
      console.log(i);
    });
    /* This and that... */
  };
};

In terms of this function alone, i is the same value that is passed when calling this function, so for example, slide("666") will appear on the console. The problem is that slide() is called only once from the entire source, and i is assigned only once.

It's like this.

If all you need was the cause of this problem itself, this would probably have been the answer.

Then, can you solve everything if you fix the slide(slide index) function well? I don't think so. It's weird to just randomly assign "how many slides do you show" in the first place. Because sliding involves three slides: the slide you see now, the slide you want to show, and the slide you saw. (Think carefully.)
In that sense, why don't you just rebuild it overall? In the case of the jquery slider that I used to work with, I didn't save the number of times the slider is floating as a variable and treated it as a class dynamic assignment (although it's not one or two places to fix it). And if this is not for study purposes... There are a lot of plug-ins that came out well, so look for them and use them.


2022-09-21 16:04

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.