如何为段落中的每个句子添加递增ID



我可以用span标记替换标点符号并分隔句子,但我试图为每个句子增加一个id,但它只对第一个有效。

$('.whatever').each(function(index) {
     var sentences = $(this).html().replace(/([^.!?]*[^.!?s][.!?]['"]?)(s|$)/g, 
     '<span id="'+index+'">$1</span>$2<SENTENCE_END>');
     $(this).html(sentences);
});

谢谢你的任何想法。

如果所有文本都在#whatever中,则需要首先按句点分割文本,然后迭代每个句点以添加<spans>

这里有一个例子:

// set counter
var j = 0;
// get text from div
var sentences = $('#whatever').text().trim();
// split text by "."
var sentences = sentences.split('.');
// empty the output div
$('#whatever').empty();
// for each sentence, check for blank sentence,
// add span with counter number, trim spaces,
// add leading space if this is not the first sentence,
// add "." at the end of sentence, output to div
$(sentences).each(function () {
    if (this.trim()!='') {
        $('#whatever').append( (j>0?" ":"") + '<span class="sentence" id="sentence_' + j + '">' + this.trim() + '.</span>');
        j++;
    }
});

http://jsfiddle.net/FrDzL/1/

为什么要使用id选择器?id选择器$('#whatever')仅选择一个元素(与页面上的id匹配的第一个元素)。因此,每个循环只执行一次(这就是为什么它只在第一个循环中工作)。修改您的html代码以使用类,并选择使用$('.anything').

ID选择器("#ID")

选择具有给定id属性的单个元素。

来源:http://api.jquery.com/id-selector/

尝试以下

HTML

<p class="whatever">hej</p>
<br>
<p class="whatever">hej</p>
<br>
<p class="whatever">hej</p>

JS-

var j = 0;
$('.whatever').each(function() {
     var sentences = $(this).html().replace('hej','nej');
     j++;
     $(this).html(sentences);
});

JSFiddle


最后,您的示例的工作代码

var j = 0;
$('.whatever').each(function() {
    var sentences = $(this).html().replace(/([^.!?]*[^.!?s][.!?]['"]?)(s|$)/g, 
 '<span class="sentence" id="'+j+'">$1</span>$2<SENTENCE_END>');
    j++;
    $(this).html(sentences);
});

最新更新