Change button text (show / hide/ show) on click in

2020-06-04 07:59发布

I am working on this fiddle: http://jsfiddle.net/cED6c/7/ I want to make the button text change on click and I tried using the following code:

<input type="button" class="reveal" onClick="this.value=this.value=='Show Answer'?'Hide Answer':'Show Answer'" value="Show Answer">

However, it does not work. How should I implement this? Any help would be great.

3条回答
我想做一个坏孩纸
2楼-- · 2020-06-04 08:27

Very easy to change the text using jQuery.

Working example here. http://jsfiddle.net/vp7Y7/

$('.reveal').click(function() {
    if ($(this).text() === 'Show Answer') {
         $(this).text('This is NEW TEXT!!! It Worked!');
    }
    else {
        $(this).text('Show Answer');
    }
});
查看更多
放荡不羁爱自由
3楼-- · 2020-06-04 08:28

You need to add this code:

if ($.trim($(this).text()) === 'Show Answer') {
    $(this).text('Hide Answer');
} else {
    $(this).text('Show Answer');        
}

You can see it at work:

http://jsfiddle.net/cED6c/13/

I add the trim function cause in the html you got space after the Show Answer.

查看更多
4楼-- · 2020-06-04 08:31

something easy like this

 $(document).ready(function () {
    $('a.edit').click(function () {
        var txt = $(this).text();
        txt = (txt !='cancel') ? 'cancel' : 'edit';
        $(this).text(txt);
        $('.editForm').toggle(300);
     });
});
查看更多
登录 后发表回答