简体   繁体   中英

How to change text of an <a> once clicked?

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?

You can change the innerHTML via JavaScript after the click

with jQuery:

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

Yes, this is quite trivial with some JavaScript. I'm going to assume that you're using an e-commerce plugin and that there's the possibility there may be more than one button on the page. You can just get a nodeList of all the buttons and loop through it, adding an onclick function to each one. You don't need jQuery for this specifically.

Take the following snippet:

 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> 

Using Javascript, click event handler

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM