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