简体   繁体   中英

Javascript function for simple slider not executing onclick

Hello and thanks for looking up. I have decided to learn Javascript by trial and error and Googling the stuff that I need. So far so good, but when I tried something a bit tricky, a slider, things got tough.

I dont really have good knowledge about syntax in Javascript and how expressions should be written in functions but I am trying.

So here we have a simple 4 images in a div with 2 arrows slider. When we click the arrow we want the counter to decrease by 1, we want to be sure it doesnt equal 0 and if it does we change it to 4, and when this is done we give the respective image ( img[counter] ) az index of 50 for example. But it doesnt work. For some reason.

Here is a fiddle of the whole thing and hope I dont trouble you guys too much with this.

https://jsfiddle.net/wu2Lysrv/3/

function slideEngine() {
    var img1 = document.querySelector("#img1");
    var img2 = document.querySelector("#img2");
    var img3 = document.querySelector("#img3");
    var img4 = document.querySelector("#img4");
    var counter = 1;

    function slideL() {
        counter--;
        if (counter == 0) {
            counter = 4;
        }
        img[counter].setAttribute("z-index", "50");
    }
}

I would understand if someone goes aggro, since I bet this piece of code over there is very very wrong. Still I would like to learn how do I do it right.

The slideL function lives inside slideEngine , so your html doesn't have direct access to it.

One potential fix is to simply remove the wrapping function, since it doesn't seem to be used anywhere. However, there are other issues with the code that will prevent it from working. I've attempted to fix some below.

var img1 = document.querySelector("#img1");
var img2 = document.querySelector("#img2");
var img3 = document.querySelector("#img3");
var img4 = document.querySelector("#img4");
var counter = 1;

function slideL() {
    counter--;
    if (counter == 0) {
        counter = 4;
    }
    window['img'+counter].style.zIndex = 50;
}

I didn't tes this, but try it out.

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