0

p文字列を入れるにdivは、次のように jquery の wrap() 関数を使用できます。

 $('p').wrap("<div></div>");

文字列 'p' をすべて html タグで囲む方法はありますか?

<html>
    <head>

    </head>
    <body>

        bla bla bla Hello world other words and etc and again Hello world

    </body>
</html>

この HTML ドキュメントには「Hello world」が 2 つありますが、どうすればそれらをpタグに入れることができますか?

必要な html の結果は次のとおりです。

bla bla bla `<p>Hello world</p>` other words and etc and again `<p>Hello world</p>`
4

3 に答える 3

2

あなたの例では..正規表現を使用してこのようにすることができます

$('body').html(function(i,v){
  return v.replace(/Hello world/g,'<p>Hello world</p>');
});

フィドル

または分割を使用して

$('body').html(function(i,v){
  return v.split('Hello world').join('<p>Hello world</p>');
});

フィドル

于 2013-01-11T22:29:41.290 に答える
1

私が理解していることから、HelloWorldをその段落要素に入れたいと思います。これを行うには2つの方法があります。

また

$('<p>Hello World</p>').wrap("<div></div>");

また

$('p').wrap("<div></div>").text('Hello World');
于 2013-01-11T22:13:03.930 に答える
1

したがって、すべてのテキストノードを見つけることができます。

function forEachTextNode(f, node) {
  if (node.nodeType === 3) {
    f(node);
  } else {
    for (var child = node.firstChild, next; child; child = next) {
      next = child.nextSibling;  // Grab next early in case f mutates the DOM.
      forEachTextNode(f, child);
    }
  }
}

次に、使用Text.splitTextして分割して、必要な単語を分割します。

function forEachSubstring(f, text, textNode) {
  var i = textNode.nodeValue.indexOf(text);
  if (i >= 0) {
    // Split before the words we want to operate on.
    textNode.splitText(i);
    var substringNode = textNode.nextSibling;
    // Split after the words we want to operate on.
    substringNode.splitText(text.length);
    var rest = substringNode.nextSibling;
    // Operate on the substring.
    f(substringNode);
    // Recurse to look for more occurrences of text.
    forEachSubstring(f, text, rest);
  }
}

次に、それらを次のように結び付けます。

function wrapInParagraph(node) {
  var wrapper = node.ownerDocument.createElement('p');
  node.parentNode.replaceChild(wrapper, node);
  wrapper.appendChild(node);
}

forEachTextNode(
    function (tn) { forEachSubstring(wrapInParagraph, "Hello, World", tn); },
    document.body);
于 2013-01-11T22:37:53.150 に答える