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

1 つのアプローチ:

$('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では欠陥があります( の 2 番目を確認してください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 に答える