簡體   English   中英

如何為段落中的每個句子添加遞增ID?

[英]How do I add an incrementing ID for each sentence in a paragraph?

我可以用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 ,則需要#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代碼以使用類,然后使用$('。whatever')選擇。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM