自动备用按钮文本,无需单击

时间:2016-06-10 14:33:58

标签: jquery html

我希望在一个按钮上以2秒的间隔交替显示两段文字。这不是点击事件。我只想让按钮在“点击这里”和“下载”之间旋转。这就是我没有运气的尝试:

<div class="assetClass customButton1_1Div" id="download_btn1">
<input type="button" class="customButton1_1" name="button1_1" value="click here" title="download_btn1" />
</div>

setInterval(toggle, 2000);
function toggle() {
document.getElementByName("button1_1").value = "download";
}

3 个答案:

答案 0 :(得分:1)

document.getElementsByName是复数并返回一个集合。

普通JS:

window.onload = function() {
  setInterval(function() {
    var but = document.getElementsByName("button1_1")[0];
    but.value = but.value == "click here" ? "download" : "click here";
  }, 1000);
}
<div class="assetClass customButton1_1Div" id="download_btn1">
  <input type="button" class="customButton1_1" name="button1_1" value="click here" title="download_btn1" />
</div>

jQuery将替代值添加到按钮:

$(function() {
  var $but = $("input[name='button1_1']").first();
  var showVal = true,butVal = [$but.val(), $but.data("alternate")];
  setInterval(function() {
    showVal=!showVal;
    $but.val(butVal[+showVal]);
  }, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="assetClass customButton1_1Div" id="download_btn1">
  <input type="button" class="customButton1_1" name="button1_1" value="Click here" title="download_btn1" data-alternate="Download" />
</div>

答案 1 :(得分:1)

这样的东西?

&#13;
&#13;
var cnt=0, arr = ['Click Here','Download'];
setTimeout(toggle, 1500);

function toggle() {
  $('.btn').val(arr[cnt]);
  cnt = (cnt > 0) ? 0 : 1;
  setTimeout(toggle, 1500);
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div class="assetClass customButton1_1Div" id="download_btn1">
  <input type="button" class="btn" value="Download" />
</div>
&#13;
&#13;
&#13;

请注意,与递归setTimeout相比,setInterval有一些缺点:

http://www.erichynds.com/blog/a-recursive-settimeout-pattern

答案 2 :(得分:1)

我使用了jQuery并更改了切换功能来检查当前值; 如果它不匹配&#34;下载&#34;,则将值设置为&#34;下载&#34;。如果匹配,则将值设置为&#34;单击此处&#34;。

https://jsfiddle.net/tg7ks727/

    $(function(){
    setInterval(ToggleText, 2000);
});

  function ToggleText() {
    var currentValue = $('input').attr("value");
    console.log(currentValue);
    if(currentValue != "download"){
       $('input').attr("value", "download");
    }
    else {
      $('input').attr("value", "click here");
    }
    }