简体   繁体   中英

How can I get the JQuery to return a valid img src?

So, I have images in a div that share the same class and one of them is selected at a time for a single view of that image. In this single view, I have arrows that I want to use to cycle between the images. The images sharing the same class have sequential alt values.

Right now, I can get the preceding alt value and set the src of the image in the single view to the source of that image. But, I can't seem to get the same effect with the following image.

    $("#leftButton").click(function(){
            var current= $('img[id="selected"]');
            var altVal=current.attr("alt").valueOf()-1;
            if(altVal>=0)
            {
                var next= $('img[alt='+altVal+']');
                current.attr("id", "");
                next.attr("id", "selected");
                $("#embiggenImage").attr("src", next.attr("src"));
            }
        }
    );

    $("#rightButton").click(function(){
            var gal=$('img[class="galleryImage"]');
            alert(gal.length);
            var current= $('img[id="selected"]');
            var altVal=current.attr("alt").valueOf()+1;
            if(altVal<gal.length)
            {
                alert("inside");
                var next= $('img[alt='+altVal+']');
                current.attr("id", "");
                next.attr("id", "selected");
                $("#embiggenImage").attr("src", next.attr("src"));
            }
        }
    );

As you can see, the code for changing the sources is exactly the same, and it reaches those two alerts fine, but returns a null source.

Edit: It seems that in the leftButton click function, alt is being properly decremented, but in the rightButton click function, when I am trying to increment alt, it instead, is appending the '1', such that the final value of altVal is '01'. This does not make any sense to me..

The problem is in the difference between these two lines:

var altVal=current.attr("alt").valueOf()-1;
var altVal=current.attr("alt").valueOf()+1;

- only has one meaning: subtract. If you call it on a string, it will be converted into a number before the operation.

+ has two meanings: add and concatenate. If you call it on a number, it adds. If you call it on a string, it concatenates. attr returns a string (as does valueOf -- I'm not sure what the point of that is), so +1 means "put add 1 to the end of the string".

You need to convert the value to a number instead. I'd use the unary + operator :

var altVal = +current.attr('alt') + 1;

If the final value in the rightButton click event for "alt" is "01", try using parseInt() before adding to it, like so:

parseInt(current.attr("alt").valueOf())+1;

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