我正在寻找如何计算某些元素中的单词,并且我成功地得到了以下内容:
var text = $("p").text();
// split() deals with multiple spaces, tabs and new lines.
var wordsCount = text.trim().split( /\s+/ ).length;
$("p").append("<br>Words: <b> " + wordsCount + "</b>");
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="p-1">These are some texts just for demo purpose</p>
&#13;
但如果段落中包含HTML标签,则如下所示:
<p class="p-1">These are <span>some texts</span> just for demo purpose</p>
或
<p class="p-1">These are <span>some <strong>texts</strong></span> just for demo purpose</p>
然后它会假设<span>some
是单个字符串,尽管它应该将some
计为第3个字。
另外例如如何根据我要求的计数来包装第3或第4个单词?
答案 0 :(得分:0)
您可以使用.contents()jquery方法
这是一个小例子
$( "p" )
.contents()
.filter(function(){
console.log($(this))
var wordsCount = $(this).text().trim().split( /\s+/ ).length;
$("p").append("<br>Words: <b> " + wordsCount + "</b>");
return this.nodeType !== 1;
})
$( "p" )
.contents()
.filter(function(){
console.log($(this))
var wordsCount = $(this).text().trim().split( /\s+/ ).length;
$("p").append("<br>Words: <b> " + wordsCount + "</b>");
return this.nodeType !== 1;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<p class="p-1">These are <span>some <strong>texts</strong></span> just for demo purpose</p>
答案 1 :(得分:0)
试试这个codepen.io或者您愿意:
$('p').each(function(i, element) {
element.innerHTML = element.innerHTML.split(/\s+/g).map(function(word) {
return '<span>'+word+'</span>';
}).join(' ');
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="p-1">These are some texts just for demo purpose</p>
<p class="p-1">These are <span>some texts</span> just for demo purpose</p>
<p class="p-1">These are <span>some <strong>texts</strong></span> just for demo purpose</p>
&#13;
或者取决于你想要的东西:
$("p").each(function(i, element) {
var text = element.innerHTML;
// split() deals with multiple spaces, tabs and new lines.
var wordsCount = text.trim().split( /\w+/ ).length -1;
element.innerHTML += "<br>Words: <b> " + wordsCount + "</b>";
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="p-1">These are some texts just for demo purpose</p>
<p class="p-1">These are <span>some texts</span> just for demo purpose</p>
<p class="p-1">These are <span>some <strong>texts</strong></span> just for demo purpose</p>
&#13;