我正在使用的replace()javascript函数看到一些非常意外的行为。本质上,如果用户在文本表单中输入 [您好] ,我想将方括号 [和] 替换为将添加的标签文本的边距,例如[Hi there]
至<div>Hi there</div>
。除所需标签外,在结束div之后也添加了<br>
标签。
这是我的代码:
javascript
$('.servicebody').each(function() {
var string = $(this).html();
$(this).html(string.replace(/\[/g, '<div class="marginme">')); // to replace opening square bracket
});
$('.servicebody').each(function() {
var string = $(this).html();
$(this).html(string.replace(/\]/g, '</div>')); // to replace closing square bracket
});
css
.marginme {
margin: 10px auto;
}
是否有任何关于为什么通过replace()函数插入<br>
标签的想法?
答案 0 :(得分:0)
我认为是因为您在标签下方插入了HTML。请尝试以下代码:
$('.servicebody').each(function() {
var string = $(this).html();
$(this).html(string.replace(/\[/g , '<div class="bulletflex"><div class="bullet"></div><div class="bullet2">').replace(/\]/g, '</div></div>'));
});
答案 1 :(得分:0)
这是我的答案:
this
存储到变量中。否则可能导致意外行为。$(lorem).ipsum();$(lorem).xyz()
至var $lorem = $(lorem);$lorem.ipsum();$lorem.xyz();
这是我的代码版本:
$('.servicebody').each(function() {
var self = this;
var $self = $(self);
var html = $self.html();
html = html.replace(/\[/g, '<div class="marginme">');
html = html.replace(/\]/g, '</div>');
$self.html(html);
});
答案 2 :(得分:-1)
我认为您可以尝试其他语法
$('.servicebody').empty().add($('</div></div>'));