2012-11-28 3 views
0

저는 jQuery의 Keyup 메소드로 작업 해 왔으며 제대로 작동하지 않습니다. 나는 Jfiddle에서 이것을 만들려고했고 거기에서 충분히 효과가 있음을 확신한다. 그러나 웹 사이트에 업로드하거나 로컬로 실행하면 작동하지 않습니다. 여기서 내가 뭘 잘못하고 있니?Keyup이 실행되지 않습니다.

<html> 
    <head> 
    <title>Untitled Document</title> 
    <script src="http://code.jquery.com/jquery-1.8.3.js"></script> 
    <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script> 
    <script> 
     $('#TAcomments').keyup(function() { 
     var textCount = $(this).val().length; 
     if(textCount <= 10) { 
      $('#TAcomments').stop().animate({ fontSize : '22px' }); 
     } 
     if(textCount > 10) { 
      $('#TAcomments').stop().animate({ fontSize : '16px' }); 
     } 
     if(textCount > 20) { 
      $('#TAcomments').stop().animate({ fontSize : '14px' }); 
     } 
     if(textCount > 30) { 
      $('#TAcomments').stop().animate({ fontSize : '10px' }); 
     } 
     }); 
    </script> 
    </head> 
    <body> 
    <textarea id="TAcomments" style="width: 400px; height: 300px; font-size: 22px;"></textarea> 
    </body> 
</html> 
+0

하나의 값을 변경하는 데 너무 많은 복사하여 붙여 넣기 작업이 필요한 이유는 무엇입니까? 변수를 사용하십시오. '$ ('# TAcomments'). stop(). animate ({fontSize : theValue}); 그리고'else if'를 사용하십시오! – epascarello

답변

3

문서가 준비 될 때까지 기다려야합니다.

$(document).ready(function(){ 
    $('#TAcomments').keyup(function() { 
     var textCount = $(this).val().length; 
     if(textCount <= 10) { 
      $('#TAcomments').stop().animate({ fontSize : '22px' }); 
     } 
     if(textCount > 10) { 
      $('#TAcomments').stop().animate({ fontSize : '16px' });    
     } 
     if(textCount > 20) { 
      $('#TAcomments').stop().animate({ fontSize : '14px' }); 
     } 
     if(textCount > 30) { 
      $('#TAcomments').stop().animate({ fontSize : '10px' }); 
     } 
    }); 
}); 

jsfiddle은 기본적으로 onload 이벤트 이후 코드를 실행합니다.

+0

굉장 감사! 문서 준비가 완료된 후이 작업을 수행해야하는 이유는 무엇입니까? – ios85

+0

HTML이 아직 제대로로드되지 않았기 때문에 기본적으로 요소가 DOM에서 아직 사용할 수 없을 때 이벤트가 정의되는 경쟁 조건이있을 수 있습니다. –

+0

문서가 나타날 때까지 기다리지 않으면 준비가되면 코드는 script 태그 위의 dom에있는 요소 만 볼 수 있습니다. 예를 들어이 경우에는 "head", "html", "title"또는 스크립트 노드 만 대상으로 지정할 수 있습니다. –

0

$(function() { /* ... */ }); 코드를 here으로 실행하면 코드가 onDomReady 일 때 작동한다는 것을 알 수 있습니다.

관련 문제