为什么用replace()函数插入了意外的<br/>?

时间:2018-07-15 15:18:44

标签: javascript jquery

我正在使用的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>标签的想法?

3 个答案:

答案 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)

这是我的答案:

  1. 我建议您使用一个功能而不是两个。就像您在示例代码中所做的那样,使用两个函数只会进行不必要的计算。
  2. 作为最佳实践,我建议您将this存储到变量中。否则可能导致意外行为。
  3. 避免多次调用jquery函数:使$(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>'));