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

Javascript 如何为段落中的每个句子添加递增ID?,javascript,html,replace,Javascript,Html,Replace,我可以用span标记替换标点符号并分隔句子,但我尝试为每个句子增加一个id,它只对第一个起作用 $('.whatever').each(function(index) { var sentences = $(this).html().replace(/([^.!?]*[^.!?\s][.!?]['"]?)(\s|$)/g, '<span id="'+index+'">$1</span>$2<SENTENCE_END>'); $(

我可以用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);
});
谢谢你的建议

试试下面的方法

HTML

最后,为您的示例编写工作代码


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

ID选择器“ID”

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

资料来源:


如果所有文本都在whater中,则需要先将文本按句点拆分,然后遍历每个要添加的句点

下面是一个例子:

// 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++;
    }
});

不,这没有什么区别。没有注意到选择器位于id上。您需要设置一个类。我会做一把小提琴。我刚试着把所有的东西都转换成类,但现在每个句子都有class=0。这很好,但它只适用于句点。怎么样s和?s我尝试在/[^.!?]*[^.!?\s][!?][']?\s |$/g上拆分,但似乎不起作用。不过方向很好,谢谢。您可能应该尝试通过将元素保存在jQuery对象中来减少选择的次数-var$whater=$'whater',我最后用match、unshift和push进行了不同的操作,谢谢。最佳答案
var j = 0;

$('.whatever').each(function() {
     var sentences = $(this).html().replace('hej','nej');
     j++;
     $(this).html(sentences);
});
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);
});
// 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++;
    }
});