【问题标题】:<br> is removed when I alert() the content of PRE tag当我 alert() PRE 标签的内容时,<br> 被删除
【发布时间】:2014-08-22 13:34:37
【问题描述】:

我想用alert()显示这个&lt;pre&gt;标签的内容:

<pre> This is the IRNIC Whois server v1.6.2.<br> Available on web at http://whois.nic.ir/<br> Find the terms and conditions of use on http://www.nic.ir/<br> <br> This server uses UTF-8 as the encoding for requests and responses.<br><br> NOTE: This output has been filtered.<br><br> Information related to 'shirzadi.ir'<br><br><br>domain:       shirzadi.ir<br>ascii:       shirzadi.ir<br>remarks: (Domain Holder) Ehsan Shirzadi<br>remarks:  (Domain Holder Address) Ferdowsi Blv , Mahdi 13 ST, Mashhad, Khorasan razavi, IR<br>holder-c:   es372-irnic<br>admin-c: es372-irnic<br>tech-c:      to52-irnic<br>bill-c:       to52-irnic<br>nserver:  wres1.irpowerweb.com<br>nserver:    wres2.irpowerweb.com<br>last-updated:   2014-01-16<br>expire-date:  2017-10-08<br>source:       IRNIC # Filtered<br><br>nic-hdl:    es372-irnic<br>person:      Ehsan Shirzadi<br>e-mail:       ehsan.shirzadi@gmail.com<br>address:    Ferdowsi Blv , Mahdi 13 ST, Mashhad, Khorasan razavi, IR<br>phone:      +985117688851<br>fax-no:        +989155066372<br>source:        IRNIC # Filtered<br><br>nic-hdl:    to52-irnic<br>org:      Fanavarie Etelaate Towseye Saman (Mihannic)<br>e-mail:      sales@mihannic.com<br>source:       IRNIC # Filtered<br><br></pre>

当我使用xx = $('pre').text()alert(xx) 阅读此内容时,&lt;br&gt; 不是,但是当我将此内容硬编码到变量中并使用 alert() 时,我可以看到它们。这里有什么问题?最后我想用&lt;br&gt;分割内容

【问题讨论】:

  • 使用.html(),.text()返回不带标签的内容
  • 这是您要寻找的最终结果jsfiddle.net/j08691/h4g0usmh
  • 当你说“我想用
    分割内容”时,你的意思是你想让 break 标记打破警告框中的文本吗?
  • 使用html() 将不起作用,除非将 br 替换为 alert 不支持标签

标签: javascript jquery


【解决方案1】:

尝试$('pre').html() 而不是 text()。这应该保留
以及其他标签/html 实体。

编辑

为了完整起见,正如 gillesc 所说,
和其他标签将在 alert() 中被剥离(因为它不支持内部 html)。因此需要结合 .html() 和 replace 方法。换行符可以替换为\n。完整代码如下所示:

xx = $('pre').html().replace(/<br>/g, "\n"); 
alert(xx);

【讨论】:

  • alert 仍然会忽略它们
  • 他问题的最后一部分“最后我想用
    分割内容”怎么样?
【解决方案2】:

text() 将去除标签,因此请改用html(),但alert 不支持标签,因此您需要先转换您的&lt;br/&gt;,然后再将其发送到laert

请参阅这篇文章,了解如何做到这一点。

HTML Tags in Javascript Alert() method

【讨论】:

    【解决方案3】:

    使用 text() 只保留内部文本,而不是 HTML 标记。

    使用 html() 并最终将每个捕获的 &lt;br /&gt; 替换为 JS 换行符,就像这里所说的:How replace HTML <br> with newline character "\n"

    【讨论】:

      【解决方案4】:

      像这样制作

       <pre id="MyID">This is Test <br /> This is test</pre>
      

      和javascript代码

       <script>
       alert(document.getElementById('MyID').innerHTML);
       </script>
      

      【讨论】:

      • 不会输出任何标签,因为alert 不支持它们
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-13
      • 1970-01-01
      • 1970-01-01
      • 2015-01-23
      • 2020-03-29
      相关资源
      最近更新 更多