我试图在几个段落中选择子字符串——方括号中的字符数,并将每个子字符串包装在 <span>
中带有类的标签,char_count
, 应用。这是其中一个的 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
中得到了正确的子串.包装本身不起作用。我做错了什么愚蠢的小事?或者这是一件愚蠢的大事?
Here是我的 fiddle 。
最佳答案
如果您喜欢冒险,您可以尝试使用范围和 surroundContents
实现解决方案,或者您可以使用 this插件,使其变得如此简单:
$(this).highlight(selected_text, { element: 'span', className: 'char_count' });
这是一个工作 fiddle :http://jsfiddle.net/Kpn7b/2/
关于javascript - jQuery:将 <span> 包裹在子字符串周围......关闭,但不完全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13184512/