如何更改<a> once clicked?

时间:2018-08-31 16:27:09

标签: javascript jquery html wordpress anchor

I have this custom anchor button on my WordPress website:

 <a class="add-to-cart-button">Buy Now</a>

I'd like it to change its text on click event. Is it possible to do with javascript/php?

3 个答案:

答案 0 :(得分:2)

点击

后,您可以通过JavaScript更改innerHTML。

使用jQuery:

$(".add-to-cart-button").click(function () {
  $(this).html('New Text');
});

答案 1 :(得分:2)

是的,这对于某些JavaScript来说是微不足道的。我将假设您使用的是电子商务插件,并且页面上可能有多个按钮。您可以只获取所有按钮的nodeList并循环遍历,向每个按钮添加一个onclick函数。您不需要为此专门使用jQuery。

使用以下代码段:

let addButtons = document.querySelectorAll('.add-to-cart-button');

for( i = 0, n = addButtons.length; i < n; ++i ){
  addButtons[i].onclick = function(){
    this.innerText = 'Thanks for buying!';
    this.classList.add( 'purchased' );
  };
}
.add-to-cart-button{background:#0095ee;padding:10px 20px;color:#fff;border-radius:3px;text-decoration:none}
.purchased { background: #ee3d96; }
.purchased:after { content: ""; }
<a href="#" class="add-to-cart-button">Buy Now</a>

<a href="#" class="add-to-cart-button">Buy Now</a>

<a href="#" class="add-to-cart-button">Buy Now</a>

答案 2 :(得分:0)

使用Javascript,单击事件处理程序

 javascript =>
 document.getElementsByClassName("add-to-cart-button").innerHTML =
 'Text you want';

 jQUery => $('.add-to-cart-button').html('Text you want');