简体   繁体   English

如何在某些元素后将文本包装在div中

[英]How to wrap text in div after certain element

I'd like to be able to wrap a div around some text after the first BR in the text. 我希望能够在文本的第一个BR之后将div包裹在一些文本周围。

So this is how it would look in the CMS for example: 因此,这就是它在CMS中的外观:

<div class="quote">
<p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus eget ligula scelerisque, tempor justo non, pretium eros. Duis luctus pulvinar posuere. Nunc quam dui, tempor eu tincidunt et, pulvinar at quam.<br /><br />

        Sed congue nisl eget libero mollis, a rhoncus odio sollicitudin. Cras aliquet mi vel diam elementum, ac vestibulum ligula imperdiet. Nulla facilisi. Praesent vestibulum nisi odio, sed scelerisque diam molestie vitae..<br /><br />

    Sed rhoncus purus eu metus elementum hendrerit. Sed scelerisque sodales eros vel tempus. Morbi tempor risus condimentum, sagittis turpis vel, auctor odio. Fusce sed lorem non dolor fringilla accumsan. Proin metus lectus.<br /><br />

    Donec malesuada elit quis nunc ultrices dictum. Nulla quis tortor sed quam aliquet tempor. Duis porta nunc non augue fermentum rutrum. Morbi imperdiet justo et est pellentesque, sed consequat neque ultricies..<br />
    </p>
</div>

and I'd like the jQuery to add a div after the first BR - so it looks like: 而且我希望jQuery在第一个BR之后添加一个div-因此它看起来像:

<div class="quote">
    <p>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus eget ligula scelerisque, tempor justo non, pretium eros. Duis luctus pulvinar posuere. Nunc quam dui, tempor eu tincidunt et, pulvinar at quam.<br />
<div id="space">
<br />

            Sed congue nisl eget libero mollis, a rhoncus odio sollicitudin. Cras aliquet mi vel diam elementum, ac vestibulum ligula imperdiet. Nulla facilisi. Praesent vestibulum nisi odio, sed scelerisque diam molestie vitae..<br /><br />

        Sed rhoncus purus eu metus elementum hendrerit. Sed scelerisque sodales eros vel tempus. Morbi tempor risus condimentum, sagittis turpis vel, auctor odio. Fusce sed lorem non dolor fringilla accumsan. Proin metus lectus.<br /><br />

        Donec malesuada elit quis nunc ultrices dictum. Nulla quis tortor sed quam aliquet tempor. Duis porta nunc non augue fermentum rutrum. Morbi imperdiet justo et est pellentesque, sed consequat neque ultricies..<br />
</div>
        </p>
    </div>

I've currently got this far with my jQuery: 目前,我的jQuery已经到此为止:

$('.quote p br').wrapAll('<div id="space"></div>');

but this just grabs all the br's and adds them together in the div not the rest of the text. 但这只是抓住了所有br,并将它们添加到div中,而不是文本的其余部分。

JS Fiddle here: http://jsfiddle.net/2pQ4r/ JS小提琴在这里: http : //jsfiddle.net/2pQ4r/

Since you are dealing with text nodes also, the element selectors will not work, you need to deal with .contents(). 由于还处理文本节点,因此元素选择器将不起作用,因此需要处理.contents()。 So one way is to find the index of first br element in the contents of quote then find all elements after that and wrap them within a div like 因此,一种方法是在quote内容中找到第一个br元素的索引,然后找到之后的所有元素并将它们包装在div例如

$('.quote').each(function () {
    var $contents = $(this).find('p').contents(),
        $br = $(this).find('p br:first'),
        index = $contents.index($br);

    $contents.slice(index + 1).wrapAll('<div id="space"></div>');
});

Demo: Fiddle 演示: 小提琴

I know you found an answer. 我知道您找到了答案。 I'm gonna leave mine below, just in case someone doesn't want to use all that fancy good-looking jQuery. 我要把我留在下面,以防万一某个人不想使用所有那些漂亮的漂亮jQuery。 It assumes your browser has Element.querySelector and Array.forEach 假设您的浏览器具有Element.querySelectorArray.forEach

(function () {
  function unconventionalMigrator(p) {
    var child, next, div;
    // get first br Element
    child = p.querySelector('br');
    // get nextSibling
    next = child = child.nextSibling;
    // make new div element to migrate children
    div = document.createElement('div');
    div.id = 'space';// IMPLEMENTATION SPECIFIC
    // migrate children
    while (child) {
      next = child.nextSibling;// save next
      div.appendChild(child);  // move current
      child = next;            // set next
    }
    // append new div Element
    p.appendChild(div);
  }
  // get p Element
  [].forEach.call(document.querySelectorAll('.quote p'),unconventionalMigrator);
}())

This wrapps only the first text node before <br /> , like you wanted (using jQuery's map function): 像您想要的那样,它仅包装<br />之前的第一个文本节点(使用jQuery的map函数):

var brs = $('.quote p br');
var nodes = brs.map(function(){
    return this.previousSibling;
});

if ( nodes.length ) {
    var firstNode = nodes[0];
    var oldText = firstNode.nodeValue;
    firstNode.nodeValue = "";
    $(firstNode).parent().prepend("<div style=\"border: 1px solid black;\">" + oldText + "</div>");
}

Fiddle 小提琴

If you really want the element after first node (as you stated), then just use this instead of last line (but I think that you meant 1st paragraph): 如果您真的想要元素第一个节点之后(如您所述),则只需使用它而不是最后一行(但我认为您的意思是第一个段落):

brs[0].remove();
$(firstNode).parent().prepend(
    "<div style=\"border: 1px solid black;\">"
    + oldText
    + "</div><br />"
);

This should help you: 这应该可以帮助您:

Use this code: http://jsfiddle.net/2pQ4r/ 使用此代码: http : //jsfiddle.net/2pQ4r/

Just wrap your text first in some container like span. 只需先将文本包装在诸如span之类的容器中即可。 And then use: $('.quote p br').next().wrapAll('<div id="space"></div>'); 然后使用: $('.quote p br').next().wrapAll('<div id="space"></div>');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM