如何在 Javascript 中随时间更改按钮文本

How to change button text over time in Javascript?

本文关键字:按钮 文本 时间 Javascript      更新时间:2023-09-26

我的页面上有一个按钮。我希望这个按钮每 2/4 秒使用 Javascript 更改一次语言。例如,当页面加载时,按钮的文本将被搜索,2或4秒后它将更改为其他语言。它不需要是一个无限循环,只需要最简单的循环。

.HTML:

<button id="search" name="q">search</button>` 

Javascript:

var x = document.getElementById('search');
//after 2 seconds:
x.innerHTML="Suchen";
//And so on

这是针对您的问题的最强大和最简单的解决方案。吉斯菲德尔。使用 setInterval() 遍历预定义的语言词典

var x = document.getElementById('search'),
    // dictionary of all the languages
    lan = ['Search',  'Suchen', 'other'],
    // hold the spot in the dictionary
    i = 1;  
setInterval(function (){
  // change the text using the dictionary
  // i++ go to the next language
  x.innerHTML = lan[i++];
  // start over if i === dictionary length
  i = lan.length === i ? 0 : i;
}, 2000);
> Demo : http://jsfiddle.net/JtHa5/

.HTML

<button id="search" name="q">Search</button>` 

Javascript:

setInterval(changeButtonText, 2000);
function changeButtonText()
{
 var btnTxt = document.getElementById('search');
    if (btnTxt.innerHTML == "Search"){
         btnTxt.innerHTML = "Suchen";
    }
    else{
         btnTxt.innerHTML = "Search";
    }
}

使用 setInterval

setInterval(function() {
    var btn = document.getElementById('search');
    if (btn.innerHTML == "search")
         btn.innerHTML = "Suchen";
    else
         btn.innerHTML = "search";
   }, 2000);
还可以

将按钮更改为input并使用 value 属性而不是 innerHTML 属性。这是Javascript:

function changeButton() {
    var btn = document.getElementById('myButton');
    if (btn.value == "Search")
        btn.value = "Suchen";
    else
        btn.value = "Search";
}
setInterval(changeButton, 2000);

和 HTML

<input type="button" id="myButton" value="Search" />