I have a button and some text on the page and I am trying to change both the button text and the page text when the button is clicked and I am trying to do this with jQuery. It works the first time the button is clicked, but then it does not change back when clicked again. Here is my code:
var button = $('.button');
var div = $('.div')
button.on('click', function() {
if(button.html('Hello World') && div.html('Hello World')) {
button.html('What\'s Up');
div.html('What\'s Up');
}
else if(button.html('What\'s Up') && div.html('What\'s Up')) {
button.html('Hello World');
div.html('Hello World');
}
});
Your first condition will always return true because it is setting the value of div
and button
, not checking for equality. Try:
if(button.html() == 'Hello World' && div.html() == 'Hello World') {
Would probably be better to use text()
instead of html()
since you aren't actually setting HTML
var text1 = 'Hello World', text2 = 'What s\'up ?';
$('button').click(function() {
if ($(this).text() == text1) {
$(this).text(text2);
$('div').html(text2);
} else {
$(this).text(text1);
$('div').html(text1);
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.