JQuery — I want to click a word to change it then click it again to change it back

核能气质少年 提交于 2019-11-30 18:55:59

问题


I want users to be able to click on 'Hello!' to make it change to 'Goodbye!' and then click it again to change it back to 'Hello!'. I've got as far as making 'Hello!' change to 'Goodbye!', but I don't know how to make the function 'repeat'.

I'm an extreme novice at this, so all help and advice is welcome!

This is as far as I've got:

HTML:

<body>
   <p id = "greeting">Hello!</p>
</body>

JQuery:

$(function(){
    $("#greeting").click(function(){
        $(this).text('Goodbye!').toggle(hide);
    });
});

回答1:


$("#greeting").click(function(){
     $(this).text(function(_, oldText) {
         return oldText === 'Goodbye!' ? 'Hello!' : 'Goodbye!';
     });
});

http://jsfiddle.net/DPeWk/




回答2:


Here is another way to do it using toggle:

The HTML

<body>
    <p>Hello!</p>
    <p style="display: none">Goodbye!</p>
</body>

The jQuery

$(document).ready(function(){ 
    $("p").click(function () {
        $("p").toggle();
    });
});

You can test it here: http://jsfiddle.net/zcQkD/2/

There is an example very similar to this on the jQuery docs for toggle: http://api.jquery.com/toggle/




回答3:


You can also try this :

$("#greeting").click(function(){
if ($(this).text() == "Hello!")
   $(this).text("Goodbye!")
else
   $(this).text("Hello!");
});


来源:https://stackoverflow.com/questions/15446454/jquery-i-want-to-click-a-word-to-change-it-then-click-it-again-to-change-it-b

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!