2012-03-22 34 views
0

我試圖在每次點擊它時更改div中的文本。我嘗試了以下,但它不工作:每次在div上使用.append()和click()時

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

任何人都可以幫助我嗎?

在此先感謝

+0

你的示例代碼有幾個語法錯誤 - 在你的'$(「div」)之後缺少大括號,單擊(fn)'和腳本末尾的額外右括號和大括號。 – 2012-03-22 13:37:43

+0

你的意思是切換?像 '$(「div」)。toggle(function(){$(this).html(「Hi」)},function(){$(this).html(「你好嗎?」)}); $(「div」)。trigger(「click」);' – 2012-03-22 13:46:06

回答

1

相反的:

if ($(this).html('hi')) 

嘗試:

if($(this).html()==='hi') 

的完整代碼(你也忘了一個 「其他」 有你的第二個 「如果」):

$(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/

0

您仍然需要返回值進行比較的.html()方法:

if ($(this).html() === 'hi'){ 
    $(this).html('how r u'); 
} else if ($(this).html() === 'how r u'){ 
    $(this).html('hi'); 
} 
0
<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> 
+1

這不會起作用,因爲條件B將由條件A觸發。需要成爲'if else' – m90 2012-03-22 13:36:10

+0

錯誤...是啊更新! – tusar 2012-03-22 13:37:51