1

私は、すべての投稿の横にある各エントリの単語数を持つブログ テーマに取り組んでいます。単語カウントを機能させることはできますが、最初のエントリでしか機能せず、すべての投稿で同じカウントが表示されます。以下のスクリプトを変更して、最も近いものを見つけてそのdiv.entrycontent中の単語をカウントする必要がありますが、すべてのエントリについてです。以下は私のエントリ マークアップ コードです。

<div class="entry">
    <div class="entryinfo">
        <script type="text/javascript">
            var text = $('.entrycontent').text();
            var wordCount = text.split(' ').length;
            $("span.words").text(wordCount + ' words');
        </script>
        <span class="words"></span>
    </div>
    <div class="entrycontent">
        Lorem ipsum dolor amet...
    </div>
</div>
4

3 に答える 3

2

を使用してループする必要があります.each()

このスクリプトをページの下部または$(document).ready(function(){...});ブロック内の上部に 1 回挿入します。

$('.entry').each(function(i,el) {
    var $entry = $(this),
        text = $entry.find('.entrycontent').text(),
        wordCount = text.split(' ').length;
    $entry.find("span.words").text(wordCount + ' words');
    $entry.find("span.chars").text(charCount); // IDs must be unique, use classes instead
});

アップデート

多くの空白が含まれている場合$entry.find('.entrycontent').text()、単語を区切るかどうかに関係なく、それらの各スペース文字で分割されます。これを試して:

$('.entry').each(function(i,el) {
    var $entry = $(this),
        text = $entry.find('.entrycontent').text(),
        wordCount = text.split(/\s+/).length;
    $entry.find("span.words").text(wordCount + ' words');
});

.split()ドキュメント

更新 2

ええと、本当の単語数が必要な場合は、.match()代わりに.split()次を使用する必要があると思います。

$('.entry').each(function(i,el) {
    var $entry = $(this),
        text = $entry.find('.entrycontent').text(),
        marr = text.match(/\w+/g) || [],  // null if no matches
        wordCount = marr.length;
    $entry.find("span.words").text(wordCount + ' words');
});
于 2012-05-25T15:43:29.460 に答える
0

おそらく、セレクターが entrycontent のクラスを持つ要素に関連付けられていることに関係があります。

次のように各エントリを繰り返すことをお勧めします。

$(".entrycontent").each(function() {
    var entryInfo = $(this).prev();
    var text = $(this).text(); 
    var wordCount = text.split(' ').length;  
    entryInfo.find("span.words").text(wordCount + ' words');  
});
于 2012-05-25T15:49:44.880 に答える
0
$('.entry').each(function() {
 var text = $(".entrycontent", this).text(),
     wordCount = text.split(/\s+/).length;
 $("span.words", this).text(wordCount + ' words');
 $("span#chars", this).text(charCount);
})
于 2012-05-25T15:43:43.247 に答える