3

いくつかの段落内の部分文字列(角かっこで囲まれた文字数)を選択し、クラスが適用された<span>タグで各文字列をラップしようとしています。char_count1つのHTMLとCSSは次のとおりです。

var select_p = $('div#promo_area div.featured_box p');
select_p.each(function() {
  var first_index = $(this).html().indexOf('[');
  var last_index = $(this).html().indexOf(']') + 1;
  var selected_text = $(this).html().substring(first_index, last_index);
  selected_text.wrap('<span class="char_count" />');
});
span.char_count {
  padding-top: 0;
  color: #ff6600 !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="promo_area">
  <h3>Featured Stories</h3>
  <div class="featured_box">
    <h4><a href="/give">Senectus et Netus</a></h4>
    <div>
      <a href="/give"><img width="207" height="139" src="http://myrussreid.com/files/2011/06/ffffff1395-207x139.jpg" class="attachment-wds_home_image wp-post-image" alt="ffffff139" title="ffffff139" /></a>
    </div>
    <p>Pellentesque habitant morbi tristique senectus et netus. [100 characters w/spaces]</p>
    <a href="/give">Please Give</a>
  </div>
  <!-- end .featured_box -->
</div>

行までは機能しているようです.wrap—で正しい部分文字列を取得しますselected_text。ラップ自体は機能しません。私が間違っているのはどんな愚かなことですか?それとも愚かな大きなことですか?

これが私のフィドルです。

4

2 に答える 2

2

範囲を使用してソリューションを実装してみて、surroundContents冒険心がある場合は、このプラグインを使用して次のように簡単にすることができます。

$(this).highlight(selected_text, { element: 'span', className: 'char_count' });

これが実用的なフィドルです:http://jsfiddle.net/Kpn7b/2/

于 2012-11-01T20:09:13.863 に答える
1

交換:

var selected_text = $(this).html().substring(first_index, last_index);

と:

var selected_text = $('<span class="char_count">').text($(this).html().substring(first_index, last_index));

あなた selected_textは文字列であり、私のものはjQueryスパンオブジェクトです。

必要に応じて、次のようなスクリプトを使用できます。

select_p.html(function(i, old) {
    return  old.replace(/(\[.*\])/gi, '<span class="char_count">$1</span>');
});
于 2012-11-01T19:57:52.980 に答える