HTML Tags in Javascript Alert() method

前端 未结 6 2080
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-01 06:17

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


et

相关标签:
6条回答
  • 2020-12-01 06:34

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

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

    ...
    .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:

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

    0 讨论(0)
  • 2020-12-01 06:39

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

    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:

    screenshot Firefox

    You get the same look in almost all browsers.

    0 讨论(0)
  • 2020-12-01 06:44

    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.

    0 讨论(0)
  • 2020-12-01 06:46

    This is not possible.

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

    0 讨论(0)
  • 2020-12-01 06:51

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

    0 讨论(0)
  • 2020-12-01 06:57

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

    0 讨论(0)
提交回复
热议问题