In JavaScript code, you can use the alert() function of the window object to display a piece of text, so as to debug the program, or warn the user about relevant information:
The code copy is as follows:
//Use window object's alert() function
window.alert("sample text");
This writing method can be simplified to use the alert() function directly:
The code copy is as follows:
//Simplified alert() usage
alert("sample text");
If you need to display text with newlines, you can use /n:
The code copy is as follows:
//Use /n in alert()
alert("The first line/nThe second line");
If you need to use tab characters, you can use /t:
The code copy is as follows:
//Use /t in alert()
alert("Alex/t50/t34/nBob/t59/t38");
Use of variables
In addition to displaying static strings, the alert() function can also accept variables and splice variable values with other strings:
The code copy is as follows:
//Use variable in alert()
var word = "life";
alert("The magic word is: " + word + ". Don't panic.");
Unfortunately, although the alert() function can accept variables, it can only do this string splicing operation; contrary to another debugging method console.log(), the alert() function does not accept the practice of passing parameters to strings. The following code is an example:
The code copy is as follows:
//Try to use parameter in alert(), will fail
var name = "Bob";
var years = 42;
alert("%s is %d years old.", name, years);
If the alert() function accepts string passes, the expected output will be "Bob is 42 years old." But in fact, the alert() function does not support this, so the final output is "%s is %d years old."
Popup window style
Since the pop-up box used by the alert() function is a browser system object rather than a web document object, it is impossible to define the style of the pop-up box by using HTML tags in the alert() function - the HTML tag will be displayed intact. For the following code:
The code copy is as follows:
//Try to use HTML tags in alert(), will fail
alert("<b>Test Text</b>");
The output is not a bold "Test Text".
If you really need to change the style of the warning box, there are two options:
1. Use Unicode characters in the alert() function. The advantage of this solution is that it is very simple to implement, but its limitations are also obvious: Unicode characters have very limited expressiveness.
2. Instead of using the alert() function, use HTML components to simulate pop-up boxes (such as using jQuery UI Dialog). The advantage of this solution is that the pop-up box will be very expressive, but the use of it will increase the complexity of the front-end code.
Conclusion
The alert() function can be used to alert users, or to debug programs. For the former, using components such as jQuery UI Dialog can greatly increase expressiveness and user experience; for the latter, because the alert() pop-up box will block the execution of JavaScript code, in many cases, using console.log() to debug the program is a better solution.