簡體   English   中英

Javascript onclick事件,每次單擊時將不同的文本寫入元素

[英]Javascript onclick event to write different text to an element with each click

我可以使用哪種Javascript代碼寫入HTML DOM? 我想創建一個按鈕,每次單擊該按鈕,它會將不同的文本寫入文檔元素? 例;

第一次點擊:

document.getElementById("paragraph").innerHTML= "This is is the initial text."

第二次點擊:

document.getElementById("paragraph").innerHTML= "This text replaces the initial text"

第三次點擊:

document.getElementById("paragraph").innerHTML= "This text replaces the text from the second click"

等等等等...

事先都沒有謝謝。

將所有文本選項添加到數組中。

設置一個變量,使每次點擊計數。

使用計數器的編號從數組中調用文本。

一些代碼:

var counter = 0;
var theArray = new Array("This is is the initial text.", "This text replaces the initial text", "This text replaces the text from the second click");

function clicked(){
   document.getElementById("paragraph").innerHTML= theArray[counter++];
}

創建一個包含所有可用文本行的數組。

然后單擊按鈕,生成一個隨機數,並用數組中的索引值替換。

var contentArray = ["This is is the initial text.", "This text replaces the initial text",    "This text replaces the text from the second click"],
length = countArray.length;

$(btn).bind('click',function(){
  var randomNumber = Math.floor(Math.random()*length);
  document.getElementById("paragraph").innerHTML = contentArray[randomNumber];
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM