[英]Making a Button and Text Change Repeatedly
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. 我在页面上有一个按钮和一些文本,当我单击按钮时,我试图同时更改按钮文本和页面文本,而我试图使用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. 您的第一个条件将始终返回true,因为它是在设置
div
和button
的值,而不是检查是否相等。 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 使用
text()
而不是html()
可能会更好,因为您实际上并未设置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);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.