Sweet Alert如何在文本中显示HTML代码

80
我正在使用 sweet-alert 插件来显示警报。使用经典配置(默认值)时,一切都正常。但是当我想在文本中添加 HTML 标签时,它会显示 <b>...</b> 而不是加粗。在寻找答案后,似乎我没有使用正确的搜索词语...
如何使 sweet alert 也能显示带有HTML代码的文本?
var hh = "<b>test</b>";
swal({
    title: "" + txt + "", 
    text: "Testno  sporocilo za objekt " + hh + "",  
    confirmButtonText: "V redu", 
    allowOutsideClick: "true" 
});

1
听起来插件使用text()来插入内容,因此HTML被编码。除非有更改此行为的选项,否则您很可能需要找到另一个插件。 - Rory McCrossan
1
感谢您的建议和帮助。我已经研究了sweet-alert.js的代码,找到了这一行:$text.innerHTML = escapeHtml(params.text || '').split("\n").join("<br>");我删除并更改了$text.innerHTML。现在它可以正常工作: $text.innerHTML = params.text; - Peter
如果你只是在改变字体,那么你应该使用 CSS(例如改变标题的 h2 类别)。我认为不关注 XSS 攻击也是一个错误之处(请参见 @teamjamieson)。 - Elin
12个回答

228

SweetAlert仓库似乎没有维护。有许多未得到回复的Pull Request,最后合并的拉取请求是在2014年11月9日。

我创建了带有HTML支持和其他自定义模态窗口选项的SweetAlert2 - 宽度、填充、Esc按钮行为等。

Swal.fire({
  title: "<i>Title</i>", 
  html: "Testno  sporocilo za objekt: <b>test</b>",  
  confirmButtonText: "V <u>redu</u>", 
});
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>


你好 @limonte,我看到了你的回答,我有一个问题,如何禁用警报?我使用sweetalert来显示“加载”消息,当Ajax请求开始时,我使用jquery(.ajaxStart),并且需要在ajax请求完成后隐藏警报。 - Fernando Bernal
1
它是否向后兼容sweetalert? - pinkpanther
2
@pinkpanther,这里有一个简短的迁移指南 - Limon Monte
我正在使用sweetalert2,并且我想在sweetalert2确认框内使用复选框,但问题是我想要使用我的自定义复选框,而在我的css中我已经禁用了复选框。为了使用我的自定义复选框,如何与sweetalert2一起使用呢?能否告诉我,我正在苦苦挣扎。 - Learning-Overthinker-Confused
1
请查看下面 @GavinR 的回答。 - Wes Dollar
显示剩余6条评论

76
最近在GitHub的主分支中合并了一个功能,允许在标题和文本参数中使用HTML。https://github.com/t4t5/sweetalert/commit/9c3bcc5cb75e598d6faaa37353ecd84937770f3d 只需使用JSON配置并将“html”设置为true即可,例如:
swal({ html:true, title:'<i>TITLE</i>', text:'<b>TEXT</b>'});

不到一周前合并了此项更改,并在README.md中提到(其中一个示例中将html设置为false,尽管没有明确说明),但它尚未在营销页面http://tristanedwards.me/sweetalert上记录。

啊,使用未合并的 requirejs P/R 还是 html-ized 主分支。决定,决定。 - pztrick
12
截至2017年,SweetAlert指南明确表示*不再使用HTML,而是使用content object*。希望这可以帮助一些人,因为这个答案有很多赞。 - Sajib Acharya
Swal 有许多版本,但这个解决方案适用于我的版本。(https://sweetalert.js.org/guides/#advanced-examples) 谢谢! - Hoàng Vũ Tgtt

43

我正在从旧版sweetalert升级,发现如何在新版本中实现(官方文档):

// this is a Node object    
var span = document.createElement("span");
span.innerHTML = "Testno  sporocilo za objekt <b>test</b>";

swal({
    title: "" + txt + "", 
    content: span,
    confirmButtonText: "V redu", 
    allowOutsideClick: "true" 
});

我尝试了所有其他建议,但只有这个对我起作用。谢谢。 - Serhat Oz

15

Sweet alerts 还有一个 'html' 选项,将其设置为 true。

var hh = "<b>test</b>";
swal({
    title: "" + txt + "", 
    html: true,
    text: "Testno  sporocilo za objekt " + hh + "",  
    confirmButtonText: "V redu", 
    allowOutsideClick: "true" 
});

对我有效的方法是将要显示的HTML片段分配给“html”属性,而不是将“html”设置为true。 - Mike Finch

11

我刚刚也遇到了这个问题。我从sweetalert 1升级到2。这个库的官方文档链接如下:https://sweetalert.js.org/guides/

文档中的 "string" 示例并不像我期望的那样工作。你不能仅仅按照文档上的方式来使用。

content: `my es6 string <strong>template</strong>` 

我的解决方法:

const template = (`my es6 string <strong'>${variable}</strong>`);
content: {
      element: 'p',
      attributes: {
        innerHTML: `${template}`,
      },
    }

关于如何做到这一点没有文档,只能通过不断尝试来实现,但至少似乎是有效的。


11

截至2018年,已经过时的是被接受的答案:

Sweetalert仍在维护中,您可以使用content选项解决原问题。


10
这个回答和SweetAlert文档对于如何使用“内容选项”来呈现HTML字符串的帮助程度差不多——并不是很大。这个回答与SweetAlert文档在这里的观点一致:https://sweetalert.js.org/guides/#upgrading-from-1x(从底部数第3个),但是两者都没有向我展示如何呈现一个HTML字符串(不是文本框或滑块,只是一个包含`<br/>`标记的字符串)。 - Tommy
1
我同意@Tommy的观点,我只是想要一个带有一个参数的es6字符串模板hello ${world},而且这些示例很奇怪。 - Shnigi
2
文档中的示例“string”并不像我预期的那样工作。你不能就这样放它。内容:my es6 string <strong>template</strong> 我的解决方法是: const template = (my es6 string <strong'>${variable}</strong>); 内容:{ element: 'p', attributes: { innerHTML: ${template}, }, } - Shnigi

4

有Sweet Alert版本1和2。实际上,版本2可以使用HTML节点工作。

我有一个带有数据表单的Sweet Alert 2,它长这个样子:

<script>
 var form = document.createElement("div");
      form.innerHTML = `
      <span id="tfHours">0</span> hours<br>
      <input style="width:90%;" type="range" name="tfHours" value=0 step=1 min=0 max=25
      onchange="window.changeHours(this.value)"
      oninput="window.changeHours(this.value)"
      ><br>
      <span id="tfMinutes">0</span> min<br>
      <input style="width:60%;" type="range" name="tfMinutes" value=0 step=5 min=0 max=60
      onchange="window.changeMinutes(this.value)"
      oninput="window.changeMinutes(this.value)"
      >`;

      swal({
        title: 'Request time to XXX',
        text: 'Select time to send / request',
        content: form,
        buttons: {
          cancel: "Cancel",
          catch: {
            text: "Create",
            value: 5,
          },
        }
      }).then((value) => {
        console.log(value);
      });

 window.changeHours = function (value){
   var tfHours = document.getElementById("tfHours");
   tfHours.innerHTML = value;
 }
 window.changeMinutes = function (value){
   var tfMinutes = document.getElementById("tfMinutes");
   tfMinutes.innerHTML = value;
 }

点此查看 Codepen 示例!


4

使用SweetAlert的html设置。

您可以将输出的HTML直接设置为此选项:

var hh = "<b>test</b>";
swal({
    title: "" + txt + "", 
    html: "Testno  sporocilo za objekt " + hh + "",  
    confirmButtonText: "V redu", 
    allowOutsideClick: "true" 
});

或者

swal({
    title: "" + txt + "", 
    html: "Testno  sporocilo za objekt <b>teste</b>",  
    confirmButtonText: "V redu", 
    allowOutsideClick: "true" 
});

3

我知道我的回答可能来得太晚了,但我找到了一个适合我的解决方法。

  1. 创建一个对象来保存你的html内容

var html_element = '<p><code>This</code> is an error</p>';

  1. 然后继续创建你的sweet alert元素
swal({
    title: "My Title", 
    text: "",  
    html: true,  
    confirmButtonText: "Okay" 
});
  1. Use javascript setTimeout function to append your html into the sweet alert. I found that setting the timeout to 210 works well

    setTimeout(function(){
         $('.sweet-alert p:eq(0)').html(html_element)
    },210);
    

你已经做到了!


1

您只需要将html变量设置为true即可。我曾经遇到过同样的问题,只需要html : true即可。

    var hh = "<b>test</b>"; 
swal({
        title: "" + txt + "", 
        text: "Testno  sporocilo za objekt " + hh + "",  
        html: true,  
        confirmButtonText: "V redu", 
        allowOutsideClick: "true"  
});
注意: html : "Testno sporocilo za objekt " + hh + "" 可能无法正常工作,因为html属性仅用于通过在Sweetalert中分配true / false值来激活此功能。
这个html : "Testno sporocilo za objekt " + hh + ""是在SweetAlert2中使用的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接