How do I change div text using array values with Javascript?

时间:2015-09-14 15:32:51

标签: javascript jquery html

I am building a website and the homepage will basically have 2 div's containing text. I want one of the divs to change every 2 seconds with values I've placed in an array

var skills = ["text1","text2","text3","text4"];
var counter = 0;
var previousSkill = document.getElementById("myGreetingSkills");
var arraylength = skills.length - 1;

function display_skills() {
    if(counter === arraylength){
        counter = 0;
    }
    else {
        counter++;  
    }
}
previousSkill.innerHTML = skills[counter];
setTimeout(display_skills, 2000);   

3 个答案:

答案 0 :(得分:2)

innerHTML is evil, use jQuery! (assuming because you have it selected as a tag)

Working fiddle

(function($) {
  $(function() {
    var skills = ["text1","text2","text3","text4"],
      counter = skills.length - 1,
      previousSkill = $("#myGreetingSkills"),
      arraylength = skills.length - 1;

    function display_skills() {
      if (counter === arraylength) {
          counter = 0;
      }
      else {
          counter++;  
      }
      previousSkill.html(skills[counter]);
    }

    display_skills();

    setInterval(function() {
      display_skills();
    }, 2000);
  });
})(jQuery);

答案 1 :(得分:0)

您需要将display_skills包裹在setTimeout()的函数中,然后使用setInterval()

var myInterval = setInterval(function(){display_skills()}, 2000);

并确保在内部调用previousSkill.innerHTML = skills[counter]; 你的间隔&#d; d函数 - 否则它只运行一次。

您可以使用window.clearInterval(myInterval);

终止间隔

答案 2 :(得分:-1)

使用array.join()。 此函数的语法是array.join(string),其中3 string是连接字符。 例: [1, 2, 3].join(" & ")将返回"1 & 2 & 3"

希望这有帮助,

Awesomeness01