如何更改网站上显示的文字?

时间:2016-05-17 19:51:51

标签: javascript html

我想要做的是更改网页上的一个文字,以便运行一系列文字。

即:

<p>My favorite hobby is <u>fishing</u>!</p>

“钓鱼”会在大约2秒后改变到爱好列表中的下一个单词。

我发现的最接近的例子就是这个

<div id="welcome">
<h3>Welcome, welcome, welcome!</h3>
<h3>Hang around a bit (for a surprise).</h3>
</div>
function ChangeIt() {
    var newcontent = '
    <h1><a href="page.html">Click here</a> ' +
    'for a web page with more of the same.</h1>';
    WriteContentIntoID("welcome",newcontent);
}
setTimeout("ChangeIt()",20000);

但我也无法让它发挥作用。

4 个答案:

答案 0 :(得分:1)

使用setInterval()

,这是一件简单的事情
    <p>My favorite hobby is <span id="ch">fishing</span>!</p>

    <script>
    var activities = ['eating', 'burping','coding'];
    var i=0;

    setInterval(function(){
        document.getElementById("ch").innerHTML = activities[i];

       if (i < activities.length-1) {
         i++;
       } else {
        i=0;
       }

   }, 1000);
   </script>

FIDDLE Demo

编辑:改为让它永远循环。

答案 1 :(得分:0)

使用此:

<p>My favorite hobby is <u>fishing</u>!</p>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

<script type="text/javascript">
function getnewword(){
   return "me";// fix this section with getting new word!
}
function ChangeIt() {
   $("p u").html(getnewword());
   setTimeout("ChangeIt()",2000);
}
setTimeout("ChangeIt()",2000);
<script>

答案 2 :(得分:0)

编程很酷。您应该尝试一些初学者JavaScript教程,如http://www.w3schools.com/js/

您必须使用脚本标记封装脚本,并且必须使用选择器(例如document.getElementById)。

这是完整的代码:

<div id="welcome">
<h3>Welcome, welcome, welcome!</h3>
<h3 id="hobby">Hang around a bit (for a surprise).</h3>
</div>
<script>
// we start with 0
var currentHobby = 0;

function ChangeIt() {
    // hobbies array
    var hobbies = ["fishing", "eating", "drinking", "programming"]; 

    // we save the current hobby in hobbyString and increment the currentHobby number
    var hobbyString = hobbies[currentHobby];
    currentHobby++;

    // if the currentHobby number is too big, we start with 0 again
    if(currentHobby >= hobbies.length) {
        currentHobby = 0;
    }

    document.getElementById("hobby").innerHTML = "My favourite hobby is " + hobbyString;
}
setInterval("ChangeIt()",2000);
</script>

答案 3 :(得分:0)

HTML PART

I am going to <span id="changingtext">InitialWord</span>

Javascript部分 - 您需要JQuery并在onLoad

上调用以下内容
var texts = ["France", "Italy", "Ireland", "Wales"];
var count = 0;
function updateval() {
    $("#changingtext").text(texts[count]);
    count < 4 ? count++ : count = 0;
}
setInterval(updateval, 2000);

使用JS Fiddle Link Click Here

单击JsFiddle上的Javascript设置按钮以检查正在使用的设置。

相关问题