2

我有一个有很多段落的网站。其中一些有文字和图像:

<p>first paragraph</p>
<p>second paragraph</p>
<p>third paragraph</p>
<p>fourth paragraph<img alt="alt" src="src"/></p>
<p>fifth paragraph</p>

我想<img>用新段落中的标签对段落进行编号:

<p id="1">first paragraph</p>
<p id="2">second paragraph</p>
<p id="3">third paragraph</p>
<p id="4">fourth paragraph</p>
<p id="5"><img alt="alt" src="src"/></p>
<p id="6">fifth paragraph</p>

请注意,如果第 4 段中的文字在图片之后,那么最终的情况应该是:

<p id="1">first paragraph</p>
<p id="2">second paragraph</p>
<p id="3">third paragraph</p>
<p id="4"><img alt="alt" src="src"/></p>
<p id="5">fourth paragraph</p>
<p id="6">fifth paragraph</p>

现在我只有这段代码,但它没有将图像添加到单独的段落中:

elem.find('p').each(function () {
    id++;
    $(this).attr('id', 'id_' + id);
});
4

2 回答 2

3

一种方法:

$('p').each(
    function(i){
        while(this.childNodes.length > 1) {
            var p = document.createElement('p');
            p.appendChild(this.childNodes[1]);
            this.parentNode.insertBefore(p,this.nextSibling);
        }
    });

$('p').attr('data-index',function(i) { return i; });​​​​​​​​​​​

JS 小提琴演示

我已经修改了第一块代码以保留 childNodes 的顺序(在使用上述代码的示例中存在缺陷(查看textNode后面的第二个img,它在错误的位置):

$('p').each(
    function(i){
        while(this.childNodes.length > 1) {
            var p = document.createElement('p');
            p.appendChild(this.lastChild);
            this.parentNode.insertBefore(p,this.nextSibling);
        }
    });

JS 小提琴演示

于 2012-09-27T19:03:51.423 回答
0

这个小提琴怎么样

$('p').each(function(index, p) {
    p.find('img').each(function() {
        if (p.text() != '') {
            var newParagraph = $('<p></p>');
            var html = p.html();
            newParagraph.append($(this));

            if (html.substring(0,1) != '<') {
                p.after(newParagraph);
            }
            else {
                p.before(newParagraph);
            }

        }         
    });
});

$('p').each(function(i) {
   $(this).attr('id', i);
});
于 2012-09-27T19:01:18.603 回答