2. Common interactive methods of JavaScript

1. Output content (document.write)

document.write() Can be used to write content directly to the HTML output stream. Simply put, it is to output content directly in the web page.

The first type : The output content is enclosed in "", and the content in the "" is directly output .

<script type="text/javascript">
  document.write("I love JavaScript!"); //The content is enclosed in "", and the content in "" is output directly.
</script>

The second : output content through variables

<script type="text/javascript">
  var mystr="hello world!";
  document.write(mystr); //Write the variable name directly and output the content stored in the variable.
</script>

The third type : output multiple contents, and connect the contents with a + sign.

<script type="text/javascript">
  var mystr="hello";
  document.write(mystr+"I love JavaScript"); //Use + sign to connect multiple contents
</script>

Fourth : output HTML tags, and work, tags are enclosed in "".

<script type="text/javascript">
  var mystr="hello";
document.write(mystr+"<br>");//After outputting hello, output a newline
  document.write("JavaScript");
</script>

Note: The problem of output spaces in JS:

When writing JS code, you can find this phenomenon:

document.write("   1      2                3  ");
Result:  1 2 3

No matter how many spaces there are in the output, the result appears to be only one space.

This is because the browser display mechanism displays multiple consecutive spaces as one space for manually typed spaces.

Solution:

1. Use the output html tag  to solve

document.write("  "+"1"+"    "+"23");
Results: 1 23

2. Use CSS styles to solve

document.write("<span style='white-space:pre;'>"+"  1        2    3    "+"</span>");
Result: 1 2 3    

 Add "white-space:pre;" style attribute on output. This style means " whitespace is preserved by the browser "

Sample code:

copy code
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>document.write</title>
  <script type="text/javascript">
    var mystr="I am";
    var mychar="JavaScript";
    document.write(mychar+"<br>");//Use document.write to output the contents of the mychar variable, and output a newline at the same time.
    document.write(mystr+mychar+"Loyal fans!");//Use document.write a statement, through the variables mystr, mychar, "Loyal fans!", output a complete sentence "I am a big fan of JavaScript!" .

  </script>
</head>
<body>
</body>
</html>
copy code

2. Warning (alert message dialog box)

When we visit the website, sometimes a small window pops up suddenly with a message text written on it. If you don't click "OK", you can't do anything with the web page. This small window is implemented using alert.

grammar:

alert(string or variable);  

See the code below:

<script type="text/javascript">
   var mynum = 30;
   alert("hello!");
   alert(mynum);
</script>

Note: alert pops up a message dialog (including an OK button).

Result: message boxes pop up in sequence

 

Notice:

1. No other operations can be performed until the "OK" button in the dialog box is clicked.

2. Message dialogs can often be used to debug programs.

3. Alert output content, which can be a string or a variable, similar to document.write.

3. Confirm (confirm message dialog)

The confirm message dialog is usually used to allow the user to make a choice, such as: "Are you right?", etc. A dialog box pops up (including an OK button and a Cancel button).

grammar:

confirm(str);

Parameter Description:

str: the text to display in the message dialog
Return value: Boolean value

return value:

Returns true when the user clicks the "OK" button
When the user clicks the "Cancel" button, return false

Note:  The return value can be used to determine what button the user clicked

See the code below:

<script type="text/javascript">
    var mymessage=confirm("Do you like JavaScript?");
    if(mymessage==true)
    { document.write("Very good, come on!"); }
    else
    { document.write("JS is powerful, learn it!"); }
</script>

result:

Note: The message dialog is exclusive, that is, the user cannot perform any other operations until the dialog button is clicked.

Fourth, ask questions (prompt message dialog box)

promptA pop-up message dialog is usually used to ask for some information that requires interaction with the user. Popup message dialog (contains an OK button, Cancel button and a text input box).

grammar:

prompt(str1, str2);

Parameter Description:

str1: the text to display in the message dialog, unmodifiable
str2: the content of the text box, which can be modified

return value:

1. Click the OK button, the content in the text box will be used as the return value of the function
2. Click the cancel button, it will return null

Take a look at the code below:

var myname=prompt("Please enter your name:");
if(myname!=null)
  { alert("Hello"+myname); }
else
  { alert("Hello my friend."); }

result:

Note: No other operations can be performed until the user clicks the button of the dialog

Sample code: Use the prompt() message box, enter your grade, and make an evaluation based on the entered grade.

copy code
1 <!DOCTYPE HTML>
 2 <html>
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 5 <title>prompt</title>
 6   <script type="text/javascript">
 7   function rec(){
 8 var score; //score variable, used to store the score value entered by the user.
 9 score = prompt("Please enter the score"); ;
10     if(score>=90)
11     {
12 document.write("You are great!");
13     }
14     else if(score>=75)
15     {
16 document.write("Yes!");
17     }
18     else if(score>=60)
19     {
20 document.write("Come on!");
21     }
22     else
23     {
24 document.write("Work hard!");
25     }
26   }
27   </script>
28 </head>
29 <body>
30 <input name="button" type="button" onClick="rec()" value="Click me to rate the score!" />
31 </body>
32 </html>
copy code

5. Open a new window (window.open)

The open() method can find an existing or newly created browser window.

grammar:

window.open([URL], [window name], [parameter string])

Parameter Description:

URL: optional parameter, the URL or path of the webpage to be displayed in the window. If this parameter is omitted, or its value is an empty string, the window will not display any documentation.
window name: optional parameter, the name of the window to be opened.
    1. The name consists of letters, numbers and underscore characters.
    2. "_top", "_blank", "_selft" have special meaning names.
       _blank: Display the landing page in a new window
       _self: Display the target web page in the current window
       _top: Displays the target page in the upper window of the framed page
    3. Only one window with the same name can be created. If you want to create multiple windows, the name cannot be the same.
    4.name cannot contain spaces.
Parameter string: optional parameters, setting window parameters, each parameter is separated by a comma.

Parameters Table:

For example: open http://www.imooc.com website, the size is 300px * 200px, no menu, no toolbar, no status bar, there is a scroll bar window:

<script type="text/javascript"> window.open('http://www.imooc.com','_blank','width=300,height=200,menubar=no,toolbar=no, status=no,scrollbars=yes')
</script>

Note: The running results consider browser compatibility issues.

Six, close the window (window.close)

close() closes the window

usage:

window.close(); //Close this window

or

<window object>.close(); //Close the specified window

For example: close the newly created window.

<script type="text/javascript">
   var mywin=window.open('http://www.imooc.com'); //Store the newly opened window object in the variable mywin
   mywin.close();
</script>

Note: The above code closes the window while opening a new window, and the opened window cannot be seen.

practise:

copy code
1 <!DOCTYPE html>
 2 <html>
 3  <head>
 4   <title> new document </title>  
 5   <meta http-equiv="Content-Type" content="text/html; charset=gbk"/>   
 6   <script type="text/javascript">  
 7     function openWindow(){
 8 // A confirmation box will pop up when a new window is opened, whether to open
 9 var message=prompt("Please enter the URL of the website you want to open","http://www.imooc.com/")
10 // Through the input dialog box, determine the open URL, the default is http://www.imooc.com/
11     if(message!=null){
12         window.open(message,'_blank','width=400,height=500,menubar=no,toobar=no')
13     }else{
14 document.write("Ah, goodbye friends!");
15     }
16
17 //Requirements for the opened window, 400 pixels wide, 500 pixels high, no menu bar, no toolbar.
18    
19     }
20     
21   </script>
22  </head>
23  <body>
24 <input type="button" value="Open website in new window" onclick="openWindow()" />
25  </body>
26 </html>
copy code

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325931865&siteId=291194637