[英]Change button text after click
我做了一個“顯示更多”按鈕,它工作正常,但我希望切換'顯示更多'>'顯示更少'>'顯示更多'......我試過這種方式,但它不起作用。 我不擅長 jquery 和 javascript。
<button type="button" id="hideshow" class="btn btn-danger btn-ver-mais">SHOW MORE </button>
jQuery(document).ready(function(){
jQuery('#hideshow').on('click', function(event) {
jQuery('#btn-show-more').toggle('show');
});
})
$(function(){
$("#hideshow").click(function () {
$(this).text(function(i, text){
return text === "SHOW MORE" , "SHOW LESS" , "SHOW MORE";
})
});
})
沒有看到您的 HTML,很難為您提供建議。 但是,我想我知道您要做什么。
顯示更多按鈕的 HTML 如下所示:
<div id="hideshow">Show More</div>
為了改變文本,我會做這樣的事情(固定)
$(function() {
$('#hideshow').click(function() {
if ($(this).text() === 'Show More') {
$(this).text('Show Less');
} else {
$(this).text('Show More');
}
});
});
按照提供的代碼進行。 該演示使用三元條件:
/* declared variable: */ var txt = /* conditional */// 'if the text of the button is SHOW MORE'...' $(this).text() === 'SHOW MORE' // '...It is now 'SHOW LESS...' ? 'SHOW LESS' // ...otherwise it is 'SHOW MORE' : 'SHOW MORE'
$('#hideshow').on('click', function(event) { // 🢃 Place this INSIDE your toggle function 🢃 var txt = $(this).text() === 'SHOW MORE' ? 'SHOW LESS' : 'SHOW MORE'; $(this).text(txt); // 🢁 Place this INSIDE your toggle function 🢁 $('#btn-show-more').toggle('show'); });
<article> <p>Chuck Norris has two speeds. Walk, and Kill. <button type="button" id="hideshow" class="btn btn-danger btn-ver-mais">SHOW MORE</button></p> <p id='btn-show-more' style='display:none'> Chuck Norris does not eat, he fights hunger When Chuck Norris finds fools' gold it automatically turns into real gold. Chuck Norris is nobody's fool, Chuck Norris once beat a wall at bloody knuckles. Chuck Norris drives an ice cream truck covered in human skulls. </p> </article> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.