2012-03-22 1 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") .Click (fn)'다음에 닫는 중괄호가 빠졌고 스크립트의 마지막에 대괄호와 중괄호가 추가되었습니다. –

+0

토글 하시겠습니까? '$ ("div"). toggle (function() {$ this) .html ("안녕하세요"), function() {$ (this) .html ("How are you? $ ("div"). trigger ("click");' –

답변

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에 의해 트리거되기 때문에 이것은 작동하지 않을 것입니다.'else else'가 필요합니다 – m90

+0

err ... 예! – tusar

관련 문제