【问题标题】:How do I replace “<br /><br />” with “<br />” in HTML using JavaScript and jQuery?如何使用 JavaScript 和 jQuery 在 HTML 中将“<br /><br />”替换为“<br />”?
【发布时间】:2016-07-08 15:03:59
【问题描述】:

我的验证摘要有时在末尾有多个 br 标签,如下所示:

<div id="ValidationSummary1" class="alert alert-error">
    Last 4-digits of Social Security number does not match 
    the Member record on file for the Member ID number you 
    have entered.<br />
    Date of Birth does not match the Member record on file for the Member ID 
    number you have entered.<br /><br />
</div>

我试图在任何时候找到两个背靠背的br 标签并将其替换为如下所示:

$('#ValidationSummary1').replace('<br /><br />', '<br />');

我知道没有replace() 函数。像这样简单的东西有什么替代品?

【问题讨论】:

标签: jquery


【解决方案1】:

使用.html()获取和设置通过标准JSreplace()传递的内容。

var div = $('#ValidationSummary1');
div.html(div.html().replace('<br /><br />', '<br />'));

【讨论】:

    【解决方案2】:

    JavaScript 本身确实 有一个replace 函数,并且鉴于jQuery 是一个构建在 JavaScript 之上的框架,你确实可以使用该方法。因此,这意味着您必须执行一个 get-manipulate-set 过程,而不是一些不错的 jQuery 方法链来完成它。

    【讨论】:

      【解决方案3】:
       var $val= $('#ValidationSummary1');
       $val.html($val.html().replace(/[<br>]+$/, '<br/>');
      

      无论有多少个
      ,它们都会被一个
      (更好的html)代替

      【讨论】:

        【解决方案4】:

        在您的情况下(需要删除 html 标签),最好的解决方案是使用 .text() 而不是 .html()。区别在于.html() 保留 html 标签,.text() 仅保留文本(删除任何 html)。

        例如:

        var value1 = $('.some_div').html(); //returns text content with HTML tags
        var value2 = $('.some_div').text(); //returns only text content
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-01-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多