문제

I've been trying to make a script to change the text of a span.

Admittedly I'm not fantastic with jQuery and have found a script. I've edited i but i cannot get the script to loop and i don't know where to even start. Any code hints or links to relevant documentation would be greatly appreciated.

Here's the jQuery so far:

function change() {
        $('#msg').html(options.pop()).fadeIn(750).delay(2000).fadeOut(750, change);
};

var options = [
    "Red Bull",
    "Smoke",
    "Babes",
    "css",
    "batman"
].reverse(); 
change();

And on jsfiddle: http://jsfiddle.net/5s8y3/214/

도움이 되었습니까?

해결책

Stop popping off the array and use an iterator instead.

var messages = ["Red Bull", "Smoke", "Babes", "css", "batman"],
    i = 0;

(function change() {
    var msg = messages[i > messages.length - 1 ? (i = 0) : i++];
    $("#msg").html(msg).fadeIn(750).delay(2000).fadeOut(750, change);
})();

JSFiddle

다른 팁

Just put a global variable:

var i = 0;

Now, add this to your change() function:

if (i < messages.length) {
    i++;
} else {
    i = 0;
}

This portion of code, will loop over your array and go back to the beginning when it has reached the end.

Then, change messages.pop() to messages[i].

Here is a JSFiddle.

The issue is that Array.pop removes the element from the array, so once it's gone through your list of messages once there's no more entries and it starts throwing errors. To get it to loop continuously, add the newly removed message to the front of the array:

function change() {
    var message = messages.pop();
    messages.unshift(messages);
    $('#msg').html(message).fadeIn(750).delay(2000).fadeOut(750, change);
};

pop() will remove the value from array. So, it works for one full cycle. After that array is empty. So, it displays blank value. actually it works in loop.

var messages = [
    "Red Bull",
    "Smoke",
    "Babes",
    "css",
    "batman"
].reverse();

var i = messages.length;
function change() {
        i=(i%messages.length);
        $('#msg').html(messages[i++]).fadeIn(750).delay(2000).fadeOut(750, change);

};
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top