[英]How to change text of an <a> once clicked?
I have this custom anchor button on my WordPress website: 我的WordPress网站上有此自定义锚按钮:
<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?
是否可以使用javascript / php?
You can change the innerHTML via JavaScript after the click 点击后,您可以通过JavaScript更改innerHTML
with jQuery: 使用jQuery:
$(".add-to-cart-button").click(function () {
$(this).html('New Text');
});
Yes, this is quite trivial with some JavaScript. 是的,这对于某些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. 您可以只获取所有按钮的nodeList并循环遍历,向每个按钮添加一个
onclick
函数。 You don't need jQuery for this specifically. 您不需要为此专门使用jQuery。
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,单击事件处理程序
javascript =>
document.getElementsByClassName("add-to-cart-button").innerHTML =
'Text you want';
jQUery => $('.add-to-cart-button').html('Text you want');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.