有效地打破html标签

时间:2012-04-19 16:12:19

标签: javascript jquery html

我有这个简单的标记:

<p> some content here </p>

我想将其分解为

<p> some </p> content <p> here </p>

使用javascript(或使用jQuery帮助)。
我想打破html p标记,以便我的特定字词(例如content)不在p之内。我想找到跨浏览器和有效的解决方案 提前谢谢。

5 个答案:

答案 0 :(得分:2)

(function () {
  $.fn.extend({
    splitAt: function (splitter) {
      this.each(function () {
        var $replacement = $(), $org = $(this);

        $.each($org.text().split(splitter), function (_, val) {
          $replacement = $replacement.add($org.clone().html(val)).add(document.createTextNode(splitter));
        });

        $org.replaceWith($replacement.slice(0, -1));
      });

      return $(this.selector, this.context);
    }
  });
}(jQuery));

$('p').splitAt('content').css('background', 'lightblue');
​

演示:http://jsfiddle.net/hSQ2m/6/

答案 1 :(得分:1)

试试这个..只需更改选择器和要从选择器中挑选和排除的单词

$('p').text($('p').text().replace('content','</p>content<p>'));

答案 2 :(得分:0)

查看Text.splitText和示例。

答案 3 :(得分:0)

试试这个:

$('p').each(function() {
    $(this).html($(this).html().replace('content','</p>content<p>'));​
})

使用每个循环选定的文本设置p元素的HTML,方法是获取其HTML并将content替换为</p>content<p>

Working example here

<强>更新

感谢@Yoshi在下面的评论...没有each()循环的更好方法:

$('p').html(function (_, html) {
  return html.replace('content','</p>content<p>');
});​

Example here

答案 4 :(得分:0)

我为你做了这个:

现场演示: http://jsfiddle.net/oscarj24/A4efg/1/

这适用于<p></p>标记内的任何文字

HTML:

<p> some content here </p>
<input type="button" id="btn" value="Do it!"/>
<br/><br/>
results will be here:
<div id="result"></div>

JS:

$('#btn').click(function(){

    // clean the "result" div each time you invoke "click"
    $('#result').html('');

    // get the text inside "<p></p>" tags
    var str = $('p').html();

    // make an array for all elements inside tag
    // result: ["", "some", "content", "here", ""]
    var substr = str.split(' ');

    // remove "space" elements from the array
    // result: ["some", "content", "here"]
    removeFromArray(substr, '');

    // populate the "result" div where i = index, e = element
    // result:
    //   some
    //   content
    //   here
    $.each(substr, function(i, e){
         $('#result').append('<p> ' + substr[i] + ' </p>');
    });
});

/* Function to remove element from js array */
function removeFromArray(arr){
    var what, a= arguments, L= a.length, ax;
    while(L> 1 && arr.length){
        what= a[--L];
        while((ax= arr.indexOf(what))!= -1){
            arr.splice(ax, 1);
        }
    }
    return arr;
}

CSS - 只是为了风格: - )

div#result{
   color: red; 
}​

希望这会有所帮助:-)