2017-01-13 3 views
0

1 요소에서 단어 개수를 가져 와서 변수에 넣으려고합니다. 그러나 나는 이것을하기위한 최선의 방법이 확실치 않습니다. 어떤 아이디어? 나는이 Question에서 답변을 시도 요소 개수 jQuery 단어 개수

var value = $('#text1').val(); 

var regex = /\s+/gi; 
var wordCount = value.trim().replace(regex, ' ').split(' ').length; 

$('#text1').html(wordCount); 

<p id="text1" class="entry">This is test text in this template</p> 

은, 아래의 코드를 추가하고이 오류가 발생했습니다. 형식 오류 : 정의되지 않은 객체없는

var word_count = $('#text1').val().replace(/^[\s,.;]+/, "").replace(/[\s,.;]+$/, "").split(/[\s,.;]+/).length; 

<!DOCTYPE html> 
 
    <html> 
 

 
    <head> 
 
     <title>text_centred</title> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 
 
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script> 
 
     <style type="text/css"> 
 
     * { 
 
      margin: 0px; 
 
      padding: 0px; 
 
     } 
 
     html, 
 
     body { 
 
      height: 100%; 
 
      width: 100%; 
 
      overflow: auto; 
 
     } 
 
     body { 
 
      background-position: center; 
 
      background-size: cover; 
 
      background-repeat: no-repeat; 
 
     } 
 
     p { 
 
      font-size: 16px; 
 
      color: #4d4d4d; 
 
      font-family: FrescoSans-Normal; 
 
      text-align: center; 
 
      line-height: 24px; 
 
      padding-bottom: 15px; 
 
      opacity: 1; 
 
     } 
 
     #textBlock { 
 
      height: 100%; 
 
      overflow: auto; 
 
      width: 100%; 
 
     } 
 
     #wrapper { 
 
      position: relative; 
 
      width: 60%; 
 
      margin: 0 auto; 
 
      max-width: 800px; 
 
      height: auto; 
 
     } 
 
     </style> 
 
     <script type="text/javascript"> 
 
     var value = $('#text1').text(); //.val() works on inputs, get the text instead 
 

 
     var regex = /\s+/gi; 
 
     var wordCount = value.trim().replace(regex, ' ').split(' ').length - 1; 
 
     // length - 1 is more accurate because 'cat dog'.split().length == 2, but theres only one space! 
 

 
     $('#text1').html(wordCount); 
 
     </script> 
 
    </head> 
 

 
    <body id="background"> 
 
     <div id="textBlock"> 
 
     <div id="wrapper"> 
 
      <p id="text1">This is test text in this template</p> 
 
     </div> 
 
     </div> 
 
    </body> 
 

 
    </html>

+3

가능한 중복 (http://stackoverflow.com/questions/8752853/how-to-count-words- [jQuery를 사용하여 자바 스크립트의 단어를 계산하는 방법] - 자바 스크립트 - 사용 - jquery) –

+0

나는 그 질문에 대한 두 가지 해결책을 시도하고 그들은 나를 위해 작동하지 않는 것 –

+1

p는 val() 속성을 가지고 있지 않다. text() – sinisake

답변

0

을 감안할 때 ('$ ('#의 텍스트 1 평가 ') 발() 교체..') :

<p id="text1">This is test text in this template</p> 

다음 코드는 트릭을 수행하는 것 같습니다. 출력은 7.

var value = $('#text1').text(); 
var regex = /\s+/gi; 
var wordCount = value.trim().split(regex).length; 
$('#text1').html(wordCount); 

jsfiddle

+0

실제 페이지 내에서 작동하지 않는 것 같아서 고맙습니다. 변수를 찾을 수 없습니다 : var value = $ ('# text1'). text(); –

+0

html에'jQuery'를 포함 시켰습니까? – Niebieski

+0

나는 여전히 같은 문제가있다. –