我有两组<ol>(有序列表),我需要数字停止在每个<li>中的最后一个<ol>处递增。我的目标是使增量在到达最后一个<li>时重新开始。

例如,如果转到Fiddle,然后单击“列表”,则返回:

1. Hello world! :)
2. Hello how are you
3. good

- Hello world! :)
- Hello how are you
- good

4. Hello world! :)
5. Hello how are you
6. good


我希望增量不影响<li>内部的所有<ol>。我希望增量在最后一个<li>处停止。在这种情况下,3. good

换句话说,这就是我要返回的内容:

1. Hello world! :)
2. Hello how are you
3. good

- Hello world! :)
- Hello how are you
- good

1. Hello world! :)
2. Hello how are you
3. good


这是我的function(){...}

function doIt() {
var input = document.getElementById("h");
var olPatt = /<ol>\s*((?:<li>.+<\/li>\s*)+)<\/ol>/g; // recognizes ordered list
var ulPatt = /<ul>\s*((?:<li>.+<\/li>\s*)+)<\/ul>/g; // recognizes unordered list
var ol = input.value.match(olPatt); // returns olPatt match from value
// var olPattAfter = ol.match(/(?:[0-9]+\.\s.+)/g); // this is supposed to return 1.,2.,3.,4.,5.,6, from ol
// var ol = result.value.match(olPatt);
// var olLi = ol.match(/<li>/g);
var ulPatt = /<ul>\s*((?:<li>.+<\/li>\s*)+)<\/ul>/g;
var i = 1;

input.value = input.value.replace(olPatt, function (n, listItems) {
    return listItems.replace(/\s*<li>/g, function () {
    return i++ + '.' + ' ';
    }).replace(/<\/li>/g, '\n');
});

input.value = input.value.replace(ulPatt, function (n, listItems) {
    return listItems.replace(/\s*<li>/g, function() {return '-' + ' ';}).replace(/<\/li>/g, '\n');
});
}

最佳答案

在replace回调中重新启动计数器:

var ulPatt = /<ul>\s*((?:<li>.+<\/li>\s*)+)<\/ul>/g;

input.value = input.value.replace(olPatt, function (n, listItems) {
    var i = 1;
    return listItems.replace(/\s*<li>/g, function () {
    return i++ + '.' + ' ';
    }).replace(/<\/li>/g, '\n');
});


fiddle

10-05 20:36
查看更多