2016-06-15 13 views
0

我从wysiwyg编辑器中提取一些html并需要解析并替换文本部分。例如,我可能会给出HTML像这样:查找并替换可能包含子元素的html元素的文本部分

<span style="font-size: 36px; line-height: 50.4px;"> 
    first text I want to replace 
    <span style="font-size: 11px;"><i><b>hello world</b></i></span> 
    second text I want to replace 
    <span style="font-size: 15px;"><i><b>foo bar</b></i></span> 
    third text I want to replace 
</span> 

比方说,我想替换父跨度的文本部分,独自离开子元素。例如,假设我想将html转换为:

<span style="font-size: 36px; line-height: 50.4px;"> 
    I replaced my first text 
    <span style="font-size: 11px;"><i><b>hello world</b></i></span> 
    I replaced my second text 
    <span style="font-size: 15px;"><i><b>foo bar</b></i></span> 
    I replaced my third text 
</span> 

替换前和替换后字符串的值在此问题中无关。我只是想知道如何找到并替换这些字符串。

我能在网上找到的最接近的事情是这个漂亮的招用jQuery:

$("#span-selector").clone().children().remove().end().text() 

然而,这将提取父所有文字,没有办法的,能够在它的位置替换修改字符串。我如何使用javascript/jQuery找到first text I want to replace并将其替换为I replaced my first text

有没有人认为这是可能的?请记住,我直接从编辑器获取html,所以它可能会让用户输入一些看起来像html的字符。所以我不知道是否手动解析手动寻找'<'和'>'会起作用。

回答

2

你可以得到使用.contents()然后使用.eq()指定索引处得到的元素,最后一个元素的所有孩子.replaceWith()

function replaceText() { 
 
    $('#parent').contents().eq(0).replaceWith('<h3>Replaced with HTML</h3>'); 
 
    $('#parent').contents().eq(2).replaceWith('replaced 2'); 
 
    $('#parent').contents().eq(4).replaceWith('replaced 3'); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<span id="parent" style="font-size: 36px; line-height: 50.4px;"> 
 
    my first text 
 
    <span style="font-size: 11px;"><i><b>hello world</b></i></span> 
 
    my second text 
 
    <span style="font-size: 15px;"><i><b>foo bar</b></i></span> 
 
    my third text 
 
</span> 
 
<button onclick="replaceText()" >Replace</button>

+0

不错,但它不会工作,如果用户包括自己的html会吗? – otajor

+0

@otajor你可以检查更新的代码。 – Kld

+0

这正是我所需要的。谢谢! – tpdietz

0

同时更换elemnt,你可以做这个选择。

DEMO

HTML:

<div class="container"> 
    <i>Lorem ipsum dolor sit amet</i>, consectetur adipisicing elit, sed 
    do eiusmod tempor incididunt ut labore et dolore magna aliqua. 
    <br><br> 

    <h1><span>My Span Content</span></h1> 

    Ut enim ad minim veniam, quis nostrud exercitation ullamco 
    laboris nisi ut aliquip ex ea commodo consequat. 
    <br><br> 
    Duis aute irure dolor in reprehenderit in voluptate velit 
    esse cillum dolore eu fugiat nulla pariatur. 
</div> 

的jQuery:

$(function() { 
    $(".container") 
    .contents() 
    .filter(function() { 
     return this.nodeType === 3 
    }).each(function(i, a) { 
     if (0 === i) { // use suitable condition, in this case, 1st 
      $(this).replaceWith('<p>my new content.</p>'); 
     } 
    }); 
}) 
相关问题