我想用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"> </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.
<span class="container">
<div class="containme">1</div>
<div class="borderme"> </div>
<div class="containme2">2</div>
</span>
Hello? Whats up, here's a fraction.
<span class="container">
<div class="containme">1</div>
<div class="borderme"> </div>
<div class="containme2">2</div>
</span>
Hello? Whats up, here's a fraction.
</span>
到这个缩短的标记
<span class="readme"> Whats up, here's a fraction. [math][top]1[/top][line][bot]2[/bot][/math] </span>
javascript replace()返回一个新的字符串,它不会改变原来的字符串,所以它可能应该是。
$(document).ready(function() {
var content = $("body").text().replace(/\[this\]/g,'<b>')
$("body").html(content);
});
请注意,括号必须被转义,否则它就会把括号里的每个字符替换成 <b>
.
这里有一个 FIDDLE
这里是 演示:
$(document).ready(function() {
// Using just replace
var text = $('body').text();
$("body").html(
text.replace(/\[this\]/g,'<b>').replace(/\[\/this\]/g,'</b>')
);
});
由于没有人解释如何用自定义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);
}