1

http://jsfiddle.net/PAWAS/3/を参照してください

JavaScript:

$(document).ready(function () {

    $.each($(".item"), function(index, value) { 
        thisEl = $(this);
        thisEl.children("strong").after("<span style='display:inline-block'>");
        $("</span>").appendTo(thisEl);

    });
});​

HTML:

<div class="item">
    <strong>Time Cond:</strong>
    MorningCheck
</div>​

する必要があります:

<div class="item">
    <strong>Time Cond:</strong>
   <span> MorningCheck</span>
</div>​

しかし、</span>テキストの前に挿入されますMorningCheck

私は何を間違えましたか?

4

1 に答える 1

2

.appendDOMを.appendTo操作し、HTML文字列を作成しないでください。同様の質問と私の答えをここで見てください:リストで.append()を使用すると、テキストが改行に配置されます

span要素内に常に1つの(空でない)テキストノードしかない場合、以下を使用して要素内に配置できます。

$(".item").each(function() {
    // get all child nodes, including text nodes
    $(this).contents().filter(function() {
        // is text node and does not only contain white space characters
        return this.nodeType === 3 && $.trim(this.nodeValue) !== '';
    }).wrap('<span style="display:inline-block"></span>'); // wrap in span
});

デモ

これにより、空でないテキストノードが検索され、span要素内にラップされます。複数のテキストノードがある場合は.last()、それらのうちの1つだけを取得するか、特定の要素の後にテキストノードをターゲットにする場合は、次のstrongようにすることができます。

$($(this).children('strong').get(0).nextSibling).wrap(...);
于 2012-08-21T00:30:24.770 に答える