如何在<p>标签中动态添加<br/>标签

时间:2015-07-16 06:39:56

标签: javascript jquery

我已经编写了html,如下面的代码行。

<div class="da-slide">
    <h2><i><asp:Label ID="lblHeading3" runat="server"></asp:Label></i></h2>
    <p>
       <i><asp:Label ID="lblDescription3" runat="server"></asp:Label> </i>
    </p>
    <div class="da-img">
       <img src="../img/bg/html5andcss3.png" alt="image01" />
    </div>
</div>

现在我想动态地在每四个单词后面的p标签中添加br标签。 请帮帮我!!!

2 个答案:

答案 0 :(得分:1)

依靠this answer了解如何获取特定文本节点的所有单词,您可以尝试以下方法:

var res = $('.da-slide p *').contents().map(function () {
    if (this.nodeType == 3 && this.nodeValue.trim() != "") //check for nodetype text and ignore empty text nodes
    return this.nodeValue.trim().split(/\W+/); //split the nodevalue to get words.
}).get(); //get the array of words.

var new_content = [];
$.each(res, function(index, value){
    index++; // avoid the modulo operation with index 0
    if(index % 4 === 0){
        new_content.push(value + '<br/>'); //add a break after every 4th word
    }else{
        new_content.push(value);
    }
    console.log(new_string);

});

$('.da-slide p i').html(new_content.join(' ')); //concatenate the new content with whitespaces

<强> Demo

<强>参考

.contents()

.map()

.get()

.each()

Node

答案 1 :(得分:1)

我不认为这是最好的方法;但是,您可以使用splitmodjoin

来实现此目的
// find all <p> elements in the 'da-slide' using jQuery and loop through each instance
$('p', '.da-slide').each(function(p_i, p_el){

    // get the text for this <p> element
    var txt = $(p_el).text();

    // split the text into individual words (assume separated by space)
    var txt_split = txt.split(' ');

    // every 4th word place a <br>
    var txt_tokenized = [];
    txt_split.forEach(function(string, index){
        if (parseInt(index) % 4 == 0){
            txt_tokenized.push('<br/>');
        }
        txt_tokenized.push(string);
    });

    // rebuild as html    
    $(p_el).html(txt_tokenized.join(' '));
});