簡體   English   中英

如何僅使用 javascript 在短時間內更改按鈕文本?

[英]How to change the button text on click for a short duration only using javascript?

我正在制作一個購物車網站,我希望我的Add to Cart按鈕在點擊它時顯示Item added ,但只有大約 2 秒鍾,然后它會變回Add to Cart 我該怎么做才能做到這一點?

試試這個:

$('button.add').click(function() {
    var self = $(this);
    if (!self.data('add')) {
        self.data('add', true);
        self.text('Item added');
        setTimeout(function() {
            self.text('Add to Cart').data('add', false);
        }, 2000);
    }
});

在普通的Javascript中,您可以使用變量來檢查按鈕是否被單擊,如果沒有,則將按鈕設置為所需的字符串並在兩秒后將其更改回來。

 document.getElementById('button').addEventListener('click', function (clicked) { return function () { if (!clicked) { var last = this.innerHTML; this.innerHTML = 'Item added'; clicked = true; setTimeout(function () { this.innerHTML = last; clicked = false; }.bind(this), 2000); } }; }(false), this); 
 <button id="button">Add to Cart</button> 

  1. 在“添加到購物車”事件處理程序中,將按鈕文本更改為“已添加項目”
  2. 在同一事件處理程序中使用:setTimeout(makeTimeoutFunc(),2000);
  3. 在makeTimeoutFunc()中,將按鈕文本更改為原始值。

單擊后,按鈕文本將被更改,按鈕也將被禁用以防止進一步操作,然后在兩秒后恢復。

 (function() { $(".btn-addcart").on("click", function() { var $this = $(this), oldText = $this.text(); $this.text("Item added"); $this.attr("disabled", "disabled"); setTimeout(function() { $this.text(oldText); $this.removeAttr("disabled"); }, 2000); }); })(); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> <button class="btn-addcart">Add to cart</button> 

試試這個:

<input type="button" id="btn"/>

$("#btn").click(function(){
$(this).val("Item Added");
setTimeout(function(){ $("#btn").val("Add to Cart"); }, 2000);         
});

這是一個只有 javascript,沒有 jquery 的版本。

<body>
  <input id ="button" type="button" value="add to cart" onclick=" tick(button)">
</body>


<script type="text/javascript">

  function tick(button){
    document.getElementById("button").value = "Item added";
    setTimeout(() => (document.getElementById("button").value  = "add to cart"), 2000);
  }

</script>

暫無
暫無

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

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