每次点击div
时,我都试图更改它中的文本。我尝试了以下操作,但不起作用:
<script>
$(document).ready(function() {
//alert('hi');
$('div').css('cursor','pointer')
$('div').append('hi')
$('div').click(function() {
if ($(this).html('hi') {
$(this).html('how r u');
}
if ($(this).html('how r u')) {
$(this).html('hi');
}
)
//$(this).html('how r u');
})
})
</script>
有人能帮我吗?
提前感谢
代替:
if ($(this).html('hi'))
尝试:
if($(this).html()==='hi')
完整代码(您还忘记了第二个"if"的"else"):
$(document).ready(function() {
$('div').css('cursor', 'pointer');
$('div').append('hi');
$('div').click(function() {
if ($(this).html() === 'hi') {
$(this).html('how r u');
} else if ($(this).html() === 'how r u') {
$(this).html('hi');
};
});
});
http://jsfiddle.net/HKWdT/
您仍然需要比较.html()
方法的返回值:
if ($(this).html() === 'hi'){
$(this).html('how r u');
} else if ($(this).html() === 'how r u'){
$(this).html('hi');
}
<script>
$(document).ready(function(){
$('div').css('cursor','pointer')
$('div').append('hi')
$('div').click(function(){
if($(this).html() == 'hi')
{
$(this).html('how r u');
}
else if($(this).html() == 'how r u')
{
$(this).html('hi');
)
});
});
</script>
这也会起作用:
<div>hi</div>
<div style="display: none">how r you</p>
<script>
$("div").click(function () {
$("div").toggle();
});
</script>