如何更改网站上显示的文本

How do I change the text displayed on a website?

本文关键字:文本 显示 何更改 网站      更新时间:2023-09-26

我想做的是将网页上的一个文本单词更改为遍历单词列表。

即:

<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);

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

以下是使用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演示

编辑:更改为使其永远循环。

使用此:

<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>

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

您必须使用script标记封装脚本,并且必须使用选择器(如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>

HTML部件

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链接点击此处

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