HTML and CSS Reference
In-Depth Information
encountered in the JavaScript code, it displays a pop-up dialog box with a message. For example, the
following code would display a simple greeting:
alert(“Hello!”);
In debugging, the alert() function is most commonly used to check the status of a variable anywhere
in your code. Consider the current time function covered earlier in an example. Say that, for some
reason you can't discern, the AM and PM part of time displays “Undefined” when the function is run.
You could use the alert() function in several places to track the content of the variable, like this:
<script type=”text/javascript”>
<!--
function getCurrentTime() {
var theAM_PM;
var theDate = new Date();
var theHour = theDate.getHours();
alert(“Before: “ + theAM_PM);
if (theHour < 12) {
theAM_PM = “AM”;
}
else {
theAM_PM = “PM”;
}
alert(“After: “ + theAM_PM);
if (theHour == 0) {
theHour = 12;
}
if (theHour > 12) {
theHour = theHour - 12;
}
var theMinutes = theDate.getMinutes();
theMinutes = theMinutes + ““;
if (theMinutes < 10) {
theMinutes = “0” + theMinutes;
}
alert(“End: “ + theAM_PM);
var theFullTime = theHour + “:” + theMinutes + “ “ + theAM_PM;
document.theForm.currentTime.value = theFullTime;
}
//-->
</script>
Additional lines were added before and after the alert() function to make it easy to identify the
inserted code. Notice that the content of the function combines text ( Before , After , and End ) plus
the variable, theAM_PM . When the button is clicked to get the current time, the dialog box will appear
three separate times. The technique of concatenating a bit of text with the variable allows you to
identify when each dialog box appears, as shown in Figure 21-6.
Search WWH ::




Custom Search