每次在div上使用.append()和click()

  • 本文关键字:append click div jquery
  • 更新时间 :
  • 英文 :


每次点击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>

最新更新