Maison > interface Web > js tutoriel > le corps du texte

JavaScript中的alert()函数使用技巧详解

高洛峰
Libérer: 2016-12-20 12:24:42
original
1794 Les gens l'ont consulté

在JavaScript代码中,可以使用window对象的alert()函数来显示一段文本,从而进行程序的调试,或者向用户警示相关信息:

//Use window object's alert() function
window.alert("sample text");
Copier après la connexion

这一写法可以简化为直接使用alert()函数:

//Simplified alert() usage
alert("sample text");
Copier après la connexion

如果需要显示带换行的文本,可以使用\n:

//Use \n in alert()
alert("The first line\nThe second line");
Copier après la connexion

如果需要使用制表符,可以用\t:

//Use \t in alert()
alert("Alex\t50\t34\nBob\t59\t38");
Copier après la connexion

变量的使用


除了显示静态字符串外,alert()函数也可以接受变量,并将变量值与其它字符串进行拼接:

//Use variable in alert()
var word = "life";
alert("The magic word is: " + word + ". Don't panic.");
Copier après la connexion

遗憾的是,尽管alert()函数可以接受变量,但能做的也仅止于这种字符串拼接操作;与另一种调试方法console.log()相反,alert()函数并不接受向字符串传参数的做法。以下述代码为例:

//Try to use parameter in alert(), will fail
var name = "Bob";
var years = 42;
alert("%s is %d years old.", name, years);
Copier après la connexion

如果alert()函数接受字符串传參,那么预期的输出结果将会是”Bob is 42 years old.”;但实际上alert()函数并不支持这么做,因此最终的输出结果为”%s is %d years old.”。


弹出窗口样式


由于alert()函数所使用的弹出框是浏览器系统对象而不是网页文档对象,因此无法通过在alert()函数中使用HTML标签来定义弹出框的样式 — HTML标签将会被原封不动的进行显示。对于以下代码:

//Try to use HTML tags in alert(), will fail
alert("<b>Test Text</b>");
Copier après la connexion

输出结果并不是加粗的”Test Text”。

如果确实需要改变警示框的样式,可以有以下两种方案:

1.在alert()函数中使用Unicode字符。这种方案的好处是实现起来非常简单,但其局限性也很明显:Unicode字符的表现力非常有限。

2.不使用alert()函数,转而用HTML组件模拟弹出框(比如使用jQuery UI Dialog)。这种方案的优势是弹出框的表现力会很强,但对其的使用会增加前端代码的复杂度。


结语

alert()函数可以用来向用户警示信息,也可以用来调试程序。对于前者,使用jQuery UI Dialog等组件能大幅增加表现力及用户体验;而对于后者,由于alert()弹出框会阻断JavaScript代码的执行,因此在很多情况下,使用console.log()来对程序进行调试是一种更好的方案。



更多JavaScript中的alert()函数使用技巧详解相关文章请关注PHP中文网!

Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!