我正在尝试在jQuery中编写一个替换函数,用html替换特定的单词。
基本上我正在尝试在加载文档时将[this]
替换为<span class='myclass'>
。我环顾四周看了几个样品,但我看到的几件事我无法开始工作。我还在学习jQuery,所以我希望有人可以给我一些建议作为尝试。
先谢谢,史蒂文。
HTML /文本:
[this]hello world![/this]
JavaScript的:
$(document).ready(function() {
// Using just replace
$("body").text().replace(/[this]/g,'<b>')
});
- 编辑 -
我使用下面的Nir演示对该功能进行了一些更改。 下面是关于我正在做什么的更多细节。我正在尝试制作一个内联部分,我已经拥有了适当的类和所做的。它在html中运行良好,但是当我运行jQuery函数时它似乎不起作用。
很明显标签已被替换,但我的css似乎并没有像我提到的那样工作。
这是指向HTML HERE
的链接并且是一个指向jsfiddle HERE
的链接$(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>
答案 0 :(得分:6)
javascript replace()返回一个新字符串,它不会改变原始字符串,所以应该是:
$(document).ready(function() {
var content = $("body").text().replace(/\[this\]/g,'<b>')
$("body").html(content);
});
请注意,括号必须进行转义,否则会用<b>
替换括号内的每个字符。
这是FIDDLE
答案 1 :(得分:2)
这是一个demo that uses regex:
$(document).ready(function() {
// Using just replace
var text = $('body').text();
$("body").html(
text.replace(/\[this\]/g,'<b>').replace(/\[\/this\]/g,'</b>')
);
});
答案 2 :(得分: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);
}