问题
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