2016-05-17 65 views
0

我搜索了很長一段時間,找不到我在找什麼,所以希望有人可以幫忙。我完全不熟悉我的腳本:)更改網站上顯示的文字

我想要做的是更改我的網頁上的文本的一個單詞,以通過單詞列表運行。

即:

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

但我無法得到它的工作的。

回答

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

編輯:改變使它永遠循環下去。

+0

除非一直到我希望它重複的變量的末尾,否則這種方法非常完美。 – salvador5266

+0

剛剛編輯.... – WillardSolutions

+1

現在它是完美的!非常感謝。希望我在小時前問過LOL! – salvador5266

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

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小提琴鏈接Click Here

點擊上的jsfiddle JavaScript的設置按鈕檢查投入使用的設置。