Javascript Alert() 方法中的 HTML 标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5278197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:27:24  来源:igfitidea点击:

HTML Tags in Javascript Alert() method

javascripthtml

提问by OrahSoft

I wanted to know if it's possible to add HTML tags to JavaScript alert()method, such as:

我想知道是否可以在 JavaScriptalert()方法中添加 HTML 标签,例如:

<b>
<ul>
<li>

etc.

等等。

Thanks for your help

谢谢你的帮助

回答by fuxia

You can use all Unicode characters and the escape characters \nand \t. An example:

您可以使用所有 Unicode 字符以及转义字符\n\t. 一个例子:

document.getElementById("test").onclick = function() {
  alert(
    'This is an alert with basic formatting\n\n' 
    + "\t? list item 1\n" 
    + '\t? list item 2\n' 
    + '\t? list item 3\n\n' 
    + '???????????????????????\n\n' 
    + 'Simple table\n\n' 
    + 'Char\t| Result\n' 
    + '\n\t| line break\n' 
    + '\t\t| tab space'
  );
}
<!DOCTYPE html>
<title>Alert formatting</title>
<meta charset=utf-8>
<button id=test>Click</button>

Result in Firefox:

结果在 Firefox:

screenshot Firefox

截图火狐

You get the same look in almost all browsers.

您在几乎所有浏览器中都会获得相同的外观。

回答by Naftali aka Neal

alert() is a method of the window object that cannot interpret HTML tags

alert() 是不能解释HTML标签的window对象的方法

回答by Peter Olson

You can add HTML into an alert string, but it will not render as HTML. It will just be displayed as a plain string. Simple answer: no.

您可以将 HTML 添加到警报字符串中,但它不会呈现为 HTML。它只会显示为一个普通字符串。简单的回答:没有。

回答by SLaks

This is not possible.

这不可能。

Instead, you should create a fake window in Javascript, using something like jQuery UI Dialog.

相反,您应该使用jQuery UI Dialog 之类的东西在 Javascript 中创建一个假窗口。

回答by Bakudan

No, you can use only some escape sequences - \nfor example (maybe only this one).

不,您只能使用一些转义序列 -例如\n(也许只有这个)。

回答by Gerardo Roza

alert()doesn't support HTML, but you have some alternatives to format your message.

alert()不支持 HTML,但您有一些替代方法来格式化您的消息。

You can use Unicode characters as others stated, or you can make use of the ES6 Template literals. For example:

您可以像其他人所说的那样使用 Unicode 字符,也可以使用ES6 模板文字。例如:

...
.catch(function (error) {
  const alertMessage = `Error retrieving resource. Please make sure:
    ? the resource server is accessible
    ? you're logged in

    Error: ${error}`;
  window.alert(alertMessage);
}

Output: enter image description here

输出: 在此处输入图片说明

As you can see, it maintains the line breaks and spaces that we included in the variable, with no extra characters.

如您所见,它保留了我们包含在变量中的换行符和空格,没有额外的字符。