使用jQuery将纯文本替换为html

问题描述 投票:9回答:3

我想用jQuery写一个replacewith函数,用html替换特定的单词。

基本上,我想替换一些类似于 [this]<span class='myclass'> 当文档被加载时。我已经找了几个样本,但我看到的几个东西我无法得到工作。我还在学习jQuery,所以我希望有人能给我一些建议,让我试试。

先谢谢你,Steven。

HTML文本。

[this]hello world![/this]​

JavaScript。

$(document).ready(function() {    
     // Using just replace
     $("body").text().replace(/[this]/g,'<b>')
});​

--EDIT--

我用Nir的演示对下面的函数做了一些改动.Heres a few more details about what I'm doing. 我想做一个inline fraction,我已经有了相应的类和什么的。它在html中工作得很好,但当我运行jQuery函数时,它似乎并不工作。

很明显标签被替换了,但我的CSS似乎并没有像我提到的那样工作。

这里有一个HTML的链接 这里

这里有一个jsfiddle的链接。这里

$(document).ready(function() {    

// Using just replace
var text = $('body').text();
$("body").html(text.replace(/\[math\]/g,'<span class="container">').replace(/\[\/math\]/g,'</span>'));

var textt = $('body').text();
$("body").html(textt.replace(/\[top\]/g,'<div class="containme">').replace(/\[\/top\]/g,'</div>'));

var textl = $('body').text();
$("body").html(textl.replace(/\[line\]/g,'<div class="borderme">&nbsp;</div>'));

var textb = $('body').text();
$("body").html(textb.replace(/\[bot\]/g,'<div class="containme2">').replace(/\[\/bot\]/g,'</div>'));
 });​

这个HTML

 <span class="readme">Whats up, here's a fraction.&nbsp;
<span class="container">
    <div class="containme">1</div>
    <div class="borderme">&nbsp;</div>
    <div class="containme2">2</div>
    </span>
 &nbsp;&nbsp;Hello? Whats up, here's a fraction.&nbsp;
    <span class="container">
    <div class="containme">1</div>
    <div class="borderme">&nbsp;</div>
    <div class="containme2">2</div>
  </span>
  &nbsp;&nbsp;Hello? Whats up, here's a fraction.&nbsp;
  </span>

到这个缩短的标记

<span class="readme"> Whats up, here's a fraction. [math][top]1[/top][line][bot]2[/bot][/math] </span>
jquery html text replace replacewith
3个回答
7
投票

javascript replace()返回一个新的字符串,它不会改变原来的字符串,所以它可能应该是。

$(document).ready(function() {    
    var content = $("body").text().replace(/\[this\]/g,'<b>')
    $("body").html(content);
});​

请注意,括号必须被转义,否则它就会把括号里的每个字符替换成 <b>.

这里有一个 FIDDLE


2
投票

这里是 演示:

$(document).ready(function() {    
    // Using just replace
    var text = $('body').text();
    $("body").html(
        text.replace(/\[this\]/g,'<b>').replace(/\[\/this\]/g,'</b>')
    );
});

0
投票

由于没有人解释如何用自定义HTML元素替换文本,现在我使用下一个功能。

replaceWithAnchor: function (el, text) {
        let anch = $('<span>');
        anch.attr('id', `my-link-1`);
        anch.text(text);

        var content = el.html().replace(text, '<span id="need-to-replace"></span>');
        el.html(content);
        el.find('#need-to-replace').replaceWith(anch);
    }
© www.soinside.com 2019 - 2024. All rights reserved.