我正在制作一个购物车网站,我想让我的添加到购物车按钮在点击后显示商品已添加,但只能持续大约2秒钟,然后再变回添加到购物车。 我该如何实现这个功能?
我正在制作一个购物车网站,我想让我的添加到购物车按钮在点击后显示商品已添加,但只能持续大约2秒钟,然后再变回添加到购物车。 我该如何实现这个功能?
在纯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>
试试这个:
$('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);
}
});
点击后,按钮文本将被更改并禁用按钮以防止进一步操作,然后在两秒钟后恢复。
(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>