Home > Web Front-end > JS Tutorial > Getting Started with JavaScript: Events, Cookies, Timing, etc._Basic Knowledge

Getting Started with JavaScript: Events, Cookies, Timing, etc._Basic Knowledge

WBOY
Release: 2016-05-16 18:00:46
Original
1185 people have browsed it

An article on "Introduction to the JavaScript language" covers many of the most basic aspects of the JavaScript language, from creating script tags to using comments, including JavaScript files into HTML documents, defining variables, using operators, defining arrays, and using conditions statements, defining functions, using loops, etc. This article starts from where the previous article ended, explaining some other basic JavaScript language concepts, and continues to provide beginners with a basic understanding of the language. The basics covered in this article will give you a better understanding of the libraries you use, know how to make decisions about whether to use them, and maybe even give you some courage to write your own. Throughout the article, examples are provided to illustrate how the language implements its various aspects.

Event

Event is a catalyst that uses JavaScript language to add any type of interaction to a web page. Each HTML element has something you can use to trigger it. Events related to JavaScript code. For example, the input field has many possible events: you can associate a focus event, which triggers JavaScript code when someone clicks or jumps to the input field, or you can associate a blur event, The JavaScript code is triggered when someone clicks outside a focused input field or jumps out of the field. After correlating events, endless possibilities emerge. For example, the blur event triggers JavaScript code that checks whether the data in the input field is valid. If it is invalid, an inline message is displayed as an automatic feedback. The following code provides an example of how the focus and blur events can be used to display default text in an input field.

onfocus="this.value = '';" onblur="if(this.value = = '')
this.value = 'Enter your email address';"/>
The input field here has a default value, so when viewing this field in a web browser, This input field displays the text "Enter your email address". In order to make the default value disappear when someone clicks or jumps to the field, the focus event is used to set the field value to an empty string. If someone clicks or jumps outside the input field, the blur event is used to display the default text again. If you don't do this, then what is left is the text they entered.

Each HTML element has events related to itself. Table 1 lists some of the most common HTML elements and their associated events.

Table 1. Common elements and their related events

Element events

body onload, onunload

input onfocus, onblur, onchange, onkeydown, onkeypress, onkeyup

form onsubmit

img onmouseover, onmouseout, onclick

try...catch and throw

try... The catch statement provides a way to detect errors in your code without sending the error to the browser or giving a custom error. If a JavaScript error is not contained within a try...catch statement, then any subsequent JavaScript code cannot be executed, and the browser has to use its own way to handle and display the error. The try part of this statement is used to execute JavaScript code, and the catch part handles errors that may occur in the try part. You can use this construct when executing code that may not work properly in some browsers. If this kind of code is placed inside the try...catch statement, then when an error is returned, it will just be ignored and not executed, and the catch part will handle the error. This error may actually give an error message, or do nothing, depending on whether the user needs to know that the error occurred.

Use try...catch to handle errors

The catch part of the statement can also contain a default error object parameter, which returns the same error object that appears in the try part of the statement Error related information. The error object has two properties: message and line. The text provided by message describes the exact error that occurred; line provides the exact line of code where the error occurred. Listing 1 shows an example try...catch statement that uses an error object to notify the error message and row number. Of course, this kind of information is only useful in debugging mode, but when you want to provide feedback to the user about an error that has occurred without relying on browser processing, these attributes become very important. It worked.

Listing 1. Using error objects in try...catch statements to debug errors

Copy code Code As follows:

try
{
// Trying to execute the error code here
}
catch(err)
{
var txt = err.message 'n';
txt = err.line;
alert(txt);
}

Use throw statements to create error exceptions

The try...catch construct provides great error handling capabilities, but you can take it one step further and use a throw statement. The throw statement allows you to create error exceptions based on certain conditions. This approach provides the best opportunity to create more user-friendly error messages that are accurate and described in plain language. Listing 2 gives a simple example of how to use the throw statement to create a condition-based error exception in the try portion of a try...catch statement.

Listing 2. Use the throw statement to create an error exception
Copy the code The code is as follows :



One thing to note is that try, catch, and throw are all lowercase: using uppercase will generate a JavaScript error.

Create pop-up boxes

JavaScript allows you to create several types of pop-up boxes. Some of the most common types - and the display boxes we are going to talk about here - are alert boxes, confirmation boxes and prompts. box.

Alert boxes

Alert boxes are not often used for their original purpose, which is a quick and easy way to display page errors, warnings, or other important messages. Alerts are currently most commonly used as a way to debug JavaScript code, so to be fair, they still have their place - it's just that this best practice is not used for the purpose for which they were originally intended. Moreover, if you use Mozilla Firefox, Apple Safari or Google Chrome, you can only use console.log for debugging purposes. So the bottom line is that when all else fails, alert boxes are a viable alternative that gets the job done. Creating an alert box is very easy: just type the alert function as a line of code and pass it a parameter, and it will open a window using whatever value you pass it. For example, you can enter a simple string, or you can use an alert box to display the value of a variable passed to it as a parameter. This is a good example of how alert boxes can be used for debugging. The following is a very basic example of how to use the alert function to generate a warning box.

alert("This can be a variable or a simple text string");
Confirmation box

Confirmation box is used to verify the choices made by the user on the website. For example, if you are a web application developer and a user chooses to delete his or her user account, it would be a good idea to confirm this choice before allowing the user to continue submitting requests.

Normally, the confirm function is written inside a conditional statement to first confirm whether the user intends to continue with the selection made, and then, based on this decision, determine whether to execute the JavaScript code. The following example uses the confirm function in a condition to determine which JavaScript code to execute:
Copy code The code is as follows :

if(confirm("Click for a response"))
{
alert('You clicked OK');
}
else
{
alert('You clicked Cancel');
}

Alert Box

Looking for a quick way to ask a question and allow the user to provide an answer Don't look for anything else, the prompt box is the most suitable. Typically, today's web developers opt for customized inline pop-ups. Although this is the case, prompt boxes still exist, and they still have their own place, especially when debugging. The prompt function is used to generate a prompt box, which has two parameters. The first parameter is a custom text string, which is usually a question or a statement prompting a certain response; the second parameter is A text string that is used as the default input text displayed in the tooltip. This default value is optional and you can change it at runtime. Below is an example of a prompt function that is used to ask a question to the user and then display the user's response in an alert box, using the value returned from the prompt function.
Copy code The code is as follows:

var response=prompt("What is your favorite band? ","Led Zeppelin");
if (response!=null && response!="")
{
alert("response: " response);
}


Using cookies

Cookies exist to store data on the client side so that your JavaScript code can retrieve and reuse the data later. If used correctly, storing data on the user's computer can have many benefits. You can use cookies to customize a user's experience, determine how to present information to them based on previous behavior, and more. Examples of cookie use include storing a visitor's name or other relevant information, which can later be displayed on the website. A cookie is a text file that is stored in the visitor's web browser and contains a name-value pair, an expiration date, and the domain and path of the server to which it should be sent.

Creating a cookie

Creating a cookie is easy: you just need to decide what information you want to store, how long you want to store it, and name the cookie for future references. . However, although it is very simple to create, the syntax is a bit tricky and you need to give it the correct syntax for it to work properly. The code below shows an example of how to create a cookie and store data in it.

document.cookie =
'cookiename=cookievalue; expires=Sat, 3 Nov 2001 12:30:10 UTC; path=/'
The first part of the string stored in the cookie is a For the name-value pair, that is, cookiename=cookievalue, a semicolon (;) separates the name-value pair from the second part. The second part of the string is the expiration date written in the correct format, followed by a semicolon to separate it from the third and final part, which is the path.

Retrieving data from a cookie

The syntax required to store data in a cookie is a bit cumbersome, but retrieving the cookie's value by name at a later time But it is very easy. Here's how to retrieve cookie values ​​by name.

alert(document.cookie);
This code obtains cookies from the current domain; however, there may be multiple cookies stored in the domain. document.cookie is an array, so to retrieve a specific For cookies, you need to find the target correctly. You're in luck: The custom function in Listing 3 makes this process easy. Just pass in the cookie name as a parameter and receive the cookie value.

Listing 3. Retrieving data from stored cookies
Copy code Code As follows:

function getCookie(c_name)
{
var i,x,y;
var cookieArray = document.cookie.split(";");
for (i=0;i
{
x = cookieArray[i].substr(0,cookieArray[i].indexOf("="));
y = cookieArray[i].substr( cookieArray[i].indexOf("=") 1);
x = x.replace(/^s |s $/g,"");
if(x == c_name)
{
return unescape(y);
}
}
}
alert(getCookie('cookiename'));

As you can see, cookies provide powerful capabilities for creating a customized experience for your visitors, or they can simply store data for later use.

Timing

JavaScript provides several functions that allow you to control and set the execution time of certain actions. The most common of these functions are:

1. setInterval

2. clearInterval

3. setTimeout

4. clearTimeout

setInterval function

In some cases, JavaScript code needs to be executed repeatedly without any user interaction. The setInterval function allows you to do this easily. setInterval has two required and one optional parameters. The first required parameter is the code you want to execute repeatedly. The second parameter is milliseconds (milliseconds), which defines the time for each execution of the JavaScript code. Interval duration. The third optional parameter is an actual parameter that can be passed to the function call specified by the code parameter. The interval you set may seem a bit strange at first because it is defined in milliseconds. So if you want it to run every one second, that would be 1000 milliseconds, two seconds would be 2000 milliseconds, and so on. Table 2 lists each parameter and its role in the setInterval function.

Table 2. Available parameters of the setInterval function

Parameter required or optional Description

code Required setInterval function JavaScript code to be executed ;

This code can be customized or a function call.

milliseconds Required The length of time between each code execution, in milliseconds.

argument Optional is a very useful parameter. When a function is used as a code parameter,

can be used to pass the actual parameters to the function.

The following code provides an example of how to use the setInterval function to execute another function every 10 seconds and pass a parameter to the function. In this way, the value of argument can be accessed inside the executing function. The argument can be a variable, object, or a simple text string, as shown in this example:
Copy code The code is as follows:

setInterval(myFunction, 10000, 'sample');
function myFunction(myArg)
{
alert('myFunction argument value: ' myArg);
}

If you want to terminate such an interval execution, the language also provides a function for this.

clearInterval function

To terminate the interval behavior, you need to use the clearInterval function, but you must include a variable when you initially create the interval behavior so that subsequent clearIntervals can reference it. The following code provides an example of how the clearInterval function references a variable previously set for the original setInterval:
Copy code Code As follows:

var myInterval = setInterval(myFunction, 10000, 'sample');
function myFunction(myArg)
{
alert('myFunction argument value: ' myArg) ;
clearInterval(myInterval);
}

As you can see, the initial setInterval function is assigned a variable name, and its name is myInterval. After this you can use myInterval to reference setInterval and change this variable, or use the clearInterval function to stop the initial interval execution function. In this example, the function is called only once because the clearInterval function is executed the first time the function is called.

setTimeout function

In terms of being able to execute code based on a certain time constraint, the setTimeout function is similar to the setInterval function, and even its parameters are the same as setInterval (see Table 2). However, the biggest difference is that the setTimeout function only executes the code once instead of repeatedly. The example here shows how to use the setTimeout function to execute a function after 10 seconds.
Copy code The code is as follows:

setTimeout(myFunction, 10000, 'sample');
function myFunction(myArg)
{
alert('myFunction argument value: ' myArg);
}

setTimeout is useful when you want to execute certain code but don’t want to execute it immediately. It is essentially a way to delay the execution of the code.

clearTimeout function

If for some reason, you change your mind and need to cancel the delay behavior set by setTimeout, the clearInterval function can be used to handle this work . As with the clearInterval function, assign a variable name to the setTimeout function so that clearTimeout can reference it later and stop the behavior it sets. The following code provides an example of how to use clearTimeout to stop the call to the setTimeout setting:
Copy the code The code is as follows:

var myTimeout = setTimeout(myFunction, 10000, 'sample');
function myFunction(myArg)
{
alert('myFunction argument value: ' myArg);
clearTimeout(myTimeout);
}

In this example, you assigned a variable name to the original setTimeout function, which was named myTimeout. You can then use myTimeout to reference the setTimeout function and use the clearInterval function to stop it.

Conclusion

The JavaScript language can be said to be one of the most popular languages, and now you understand why. This simple yet rich scripting language brings so many possibilities, and it provides tools that allow website visitors to interact with downloaded web pages, which is very powerful. This article laid the foundation for understanding the basic principles of the JavaScript language: the next thing to do is to put these concepts into practice and start exploring JavaScript objects.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template