前端語法整理

前言

好久都沒有更新隨筆了,一方面這段時間本身確實有所懈怠,另外一方面確實最近工做中的事情多而雜,沒有好好沉下來專一一方面的成長。其實這段時間,也並非毫無所獲,仍是發表了一些比較系統的文章(好比「大數據測試環境全量遷移docker之路」),在公司內部的論壇裏,因爲涉及一些關鍵技術和敏感信息,因此不便在此發表。另外,這段時間學習了spring-boot開發的一些知識,並將以前的關於java基礎和設計模式、以及jvm虛擬機相關的內容作了整理,放到本身的我的github上:https://github.com/znifengjavascript

最近在負責開發組裏的一個「大數據測試平臺」,用的是spring-boot,因爲常常性地要查一些前端語法,所以索性將前段時間學習的前端相關知識整理於此,同時想借此篇開啓2018年的博客之旅。php

1、HTML

參考地址:w3school_htmlcss

1.basichtml

<!DOCTYPE html>
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>

!DOCTYPE聲明瞭doc type爲HTML5
body中的內容纔是可見的
h1~h6爲標題,h1爲最大前端

2.超連接java

<a href="https://www.w3schools.com">This is a link</a>

3.圖片jquery

<img src="w3schools.jpg" alt="W3Schools.com" width="104" height="142">

4.空行(不須要end tag)git

<br>

5.attributes
屬性提供了關於元素的額外信息,定義在start tag中,相似name="value"github

href:連接地址
src:圖片地址
width: 圖片寬度(pixel)
height: 圖片高度(pixel)
alt: 圖片顯示不出時,顯示的替代文本web

6.水平線

<hr>

7.head元素
置於html和body元素之間,定義html文件的元數據(metadata)

<!DOCTYPE html>
<html>

<head>
  <title>My First HTML</title>
  <meta charset="UTF-8">
</head>

<body>

8.styles

定義元素的格式。基本格式:

<tagname style="property:value;">

其中property爲CSS屬性,value爲CSS值。

<!--背景顏色-->
<body style="background-color:powderblue;"> 
<!--字體顏色-->
<p style="color:red;">I am red</p>
<p style="color:blue;">I am blue</p>
<!--字體大小-->
<p style="font-size:36px;">I am big</p>
<p style="font-size:160%;">I am big</p>
<!--字體格式-->
<p style="font-family:courier;">I am big</p>
<!--對齊方式-->
<p style="text-align:center;">Centered paragraph.</p>
</body>

9.formatting

<b> - Bold text
<strong> - Important text
<i> - Italic text
<em> - Emphasized text
<mark> - Marked text
<small> - Small text
<del> - Deleted text
<ins> - Inserted text (下劃線)
<sub> - Subscript text(下標)
<sup> - Superscript text(上標)

10.quatation 引用

<!-- q -->
<p>WWF's goal is to: <q>Build a future where people live in harmony with nature.</q></p>
<p>Here is a quote from WWF's website:</p>

<!-- blockquote -->
<blockquote cite="http://www.worldwildlife.org/who/index.html">
For 50 years, WWF has been protecting the future of nature.
The world's leading conservation organization,
WWF works in 100 countries and is supported by
1.2 million members in the United States and
close to 5 million globally.
</blockquote>

11.Color
https://www.w3schools.com/html/html_colors.asp

<!--background -->
<!DOCTYPE html>
<html>
<body>
<h1 style="background-color:Tomato;">Tomato</h1>
<h1 style="background-color:Orange;">Orange</h1>
<h1 style="background-color:DodgerBlue;">DodgerBlue</h1>
<h1 style="background-color:MediumSeaGreen;">MediumSeaGreen</h1>
<h1 style="background-color:Gray;">Gray</h1>
<h1 style="background-color:SlateBlue;">SlateBlue</h1>
<h1 style="background-color:Violet;">Violet</h1>
<h1 style="background-color:LightGray;">LightGray</h1>
</body>
</html>

<!--text -->
<h1 style="color:Tomato;">Hello World</h1>
<p style="color:DodgerBlue;">Lorem ipsum...</p>
<p style="color:MediumSeaGreen;">Ut wisi enim...</p>

<!--border -->
<h1 style="border:2px solid Tomato;">Hello World</h1>
<h1 style="border:2px solid DodgerBlue;">Hello World</h1>
<h1 style="border:2px solid Violet;">Hello World</h1>

<!--using RGB, HEX, HSL, RGBA, HSLA-->
<h1 style="background-color:rgb(255, 99, 71);">...</h1>
<h1 style="background-color:#ff6347;">...</h1>
<h1 style="background-color:hsl(9, 100%, 64%);">...</h1>
<h1 style="background-color:rgba(255, 99, 71, 0.5);">...</h1>
<h1 style="background-color:hsla(9, 100%, 64%, 0.5);">...</h1>

12.CSS

  • Inline CSS
<h1 style="color:blue;">This is a Blue Heading</h1>
  • Internal CSS
<!DOCTYPE html>
<html>
<head>
<style>
body {background-color: powderblue;}
h1   {color: blue;}
p    {color: red;}
</style>
</head>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>
  • Extennal CSS (recommend)

test.html:

<!DOCTYPE html>
<html>
<head>
<!-- 本地引入與website同目錄的styles.css文件 -->
  <link rel="stylesheet" href="styles.css">
<!-- 本地引入與website目錄相對路徑的styles.css文件 -->  
  <link rel="stylesheet" href="/html/styles.css">
<!-- 外部引入css -->
  <link rel="stylesheet" href="https://www.w3schools.com/html/styles.css">
</head>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>

styles.css:

body {
    background-color: powderblue;
}
h1 {
    color: blue;
}
p {
    color: red;
}

/* for an element with id "p01" */
#p01 {
    color: blue;
}

/* for elements with class "error" */
p.error {
    color: red;
}

13.table

<table style="width:100%">
  <caption>User Info</caption>
  <tr>
    <th>Firstname</th>
    <th>Lastname</th> 
    <th>Age</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td> 
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td> 
    <td>94</td>
  </tr>
</table>

tr: a table row
th: a table head
td: a table data/cell
caption:標題

14.javascript

example1: show date

<!DOCTYPE html>
<html>
<body>

<h1>My First JavaScript</h1>

<button type="button"
onclick="document.getElementById('demo').innerHTML = Date()">
Click me to display Date and Time.</button>

<p id="demo"></p>

</body>
</html>

example2: change style and content

<!DOCTYPE html>
<html>
<body>

<h1>My First JavaScript</h1>

<p>JavaScript can change the content of an HTML element:</p>

<button type="button" onclick="myFunction()">Click Me!</button>

<p id="demo">This is a demonstration.</p>

<script>
function myFunction() { 
    document.getElementById("demo").innerHTML = "Hello JavaScript!";
     document.getElementById("demo").style.fontSize = "25px"; 
    document.getElementById("demo").style.color = "red";
    document.getElementById("demo").style.backgroundColor = "yellow";
}
</script>

</body>
</html>

example3: change attribute

<!DOCTYPE html>
<html>
<body>
<script>
function light(sw) {
    var pic;
    if (sw == 0) {
        pic = "pic_bulboff.gif"
    } else {
        pic = "pic_bulbon.gif"
    }
    document.getElementById('myImage').src = pic;
}
</script>

<img id="myImage" src="pic_bulboff.gif" width="100" height="180">

<p>
<button type="button" onclick="light(1)">Light On</button>
<button type="button" onclick="light(0)">Light Off</button>
</p>

</body>
</html>

15.using bootstrap CSS

<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

16.form表單提交

Test input:

<form action="/action/api">
  First name:<br>
  <input type="text" name="firstname" value="Mickey">
  <br>
  Last name:<br>
  <input type="text" name="lastname" value="Mouse">
  <br><br>
  <input type="submit" value="Submit">
</form> 
<p>If you click the "Submit" button, the form-data will be sent to a page called "/action/api".</p>

Radio Button input:

<form>
  <input type="radio" name="gender" value="male" checked> Male<br>
  <input type="radio" name="gender" value="female"> Female<br>
  <input type="radio" name="gender" value="other"> Other  
</form>

Select input:

<form action="/action_page.php">
  <select name="cars">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="fiat">Fiat</option>
    <option value="audi">Audi</option>
  </select>
  <br><br>
  <input type="submit">
</form>

Multiple Select:

<select name="cars" size="4" multiple>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="fiat">Fiat</option>
  <option value="audi">Audi</option>
</select>

textarea:

<form action="/action_page.php" target="_blank" method="get">
  <textarea name="message" rows="10" cols="30">The cat was playing in the garden.</textarea>
  <br>
  <input type="submit">
</form>

target="_blank" :默認會在當前窗口進行跳轉。若是加上此屬性,會打開一個新的空白窗口進行跳轉。

method="get"或method="post":限定http請求的方法

必須包含name屬性,不然數據不會被髮送

2、CSS

A CSS rule-set consists of a selector and a declaration block:

1.Selector

(1) element selector

p {
    text-align: center;
    color: red;
}

(2) id selector

#para1 {
    text-align: center;
    color: red;
}

(3) class selector

.center {
    text-align: center;
    color: red;
}
/* 只針對<p>生效 */
p.center {
    text-align: center;
    color: red;
}
/* group selectors */
h1, h2, p {
    text-align: center;
    color: red;
}

2.multiple stytle sheets

若是一個元素在多個css文件中被定義了屬性,則會使用最後一個加載的css文件的值

3、JavaScript

1.在HTML中,JS代碼插入在塊中。能夠插入多個js腳本,能夠放在body中也能夠放在head中,或者both。

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>

<button type="button" onclick="document.getElementById('demo').style.fontSize='35px'">Click Me!</button>

2.外部加載js代碼的方式

<script src="myScript.js"></script>

外部的js腳本不能包含script tag:

function myFunction() {
   document.getElementById("demo").innerHTML = "Paragraph changed.";
}

外部腳本的引用可使用完整的URL,或者一個相對路徑。

<script src="https://www.w3schools.com/js/myScript1.js"></script>
<script src="/js/myScript1.js"></script>
<script src="myScript.js"></script>

3.display

  • Writing into an HTML element, using innerHTML.
  • Writing into the HTML output using document.write(). ——only for testing
  • Writing into an alert box, using window.alert().
  • Writing into the browser console, using console.log(). --for debugging purposes
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My First Paragraph</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>

<script>
document.write(5 + 6);
</script>

<script>
window.alert(5 + 6);
</script>

<script>
console.log(5 + 6);
</script>

</body>
</html>

4.在HTML中,JavaScript程序是由瀏覽器來執行。

JS Statements組成:

  • Values
  • Operators
  • Expressions
  • Keywords
  • Comments

4.1 Values

常量:

  1. 數字: 10.50、1001
  2. 字符:"zni"、'zni'

變量:

//沒有賦值的變量默認值爲undefined
var x;
//賦值參數
x = 6;
//在一行中聲明多個變量
var person = "John Doe", carName = "Volvo", price = 200;

4.2 Operators

( + - * / ) =
//x1="John Doe"
var x1 = "John" + " " + "Doe";
//x2=10
var x2 = 5 + 2 + 3;
//x3="523"
var x3 = "5" + 2 + 3;
//x4="55"
var x4 = 2 + 3 + "5";
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (Remainder)
++ Increment
-- Decrement
== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
? ternary operator
&& logical and
|| logical or
! logical not
typeof Returns the type of a variable
instanceof Returns true if an object is an instance of an object type

位操做:

4.3 Expressions

一條表達式由values和operators組成

4.4 Keywords

關鍵字,如var

4.5 Comments

註釋

var x = 5;   // I will be executed
// var x = 6;   I will NOT be executed

4.6 Identifiers標識符

identifier: values(keywords、functions、labels)的命名

規則:

  • 以字母或下劃線或$開頭
  • 後面跟字母、數字、下劃線或$
  • 區分大小寫
  • 不容許出線中劃線-,專門用做減法操做符

推薦寫法:firstName,小寫字母開頭的駝峯式命名

5.關鍵字keywords

Keyword Description
break Terminates a switch or a loop
continue Jumps out of a loop and starts at the top
debugger Stops the execution of JavaScript, and calls (if available) the debugging function
do ... while Executes a block of statements, and repeats the block, while a condition is true
for Marks a block of statements to be executed, as long as a condition is true
function Declares a function
if ... else Marks a block of statements to be executed, depending on a condition
return Exits a function
switch Marks a block of statements to be executed, depending on different cases
try ... catch Implements error handling to a block of statements
var Declares a variable

6.註釋

// Change heading:

/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
in my web page:
*/

7.data types

var length = 16;                               // Number
var lastName = "Johnson";                      // String
//Object properties are written as name:value pairs, separated by commas.
var x = {firstName:"John", lastName:"Doe"};    // Object
//first item is [0], second is [1], and so on.
var cars = ["Saab", "Volvo", "BMW"];           // Arrays,

typeof操做符

typeof ""                  // Returns "string"
typeof "John"              // Returns "string"
typeof "John Doe"          // Returns "string"

undefined和 null的區別

typeof undefined           // undefined
typeof null                // object

null === undefined         // false
null == undefined          // true

8.function

function name(parameter1, parameter2, parameter3) {
    code to be executed
}
function toCelsius(f) {
    return (5/9) * (f-32);
}
//返回函數結果25
document.getElementById("demo").innerHTML = toCelsius(77);
//返回函數的object自己:function toCelsius(f) { return (5/9) * (f-32); }
//document.getElementById("demo").innerHTML = toCelsius;

9.object

var person = {
    firstName : "John",
    lastName  : "Doe",
    age       : 50,
    eyeColor  : "blue",
    //method
    fullName : function() {
       return this.firstName + " " + this.lastName;
    }
};

document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
//call method
document.getElementById("demo").innerHTML = person.fullName();

10.域:local 和 global

  • 大部分同通常的變成語言
  • 注意:沒有用var聲明的變量,若是被直接賦值,會自動成爲全局變量
myFunction();

// code here can use carName as a global variable
document.getElementById("demo").innerHTML = "I can display " + carName;

function myFunction() {
    carName = "Volvo";
}

變量生命週期:

從變量聲明開始,local變量會在函數完成時被刪除,全局變量會在瀏覽器窗口關閉時被刪除。

11.Events

  • An HTML web page has finished loading
  • An HTML input field was changed
  • An HTML button was clicked
<element event='some JavaScript'>
<element event="some JavaScript">

button

<! --change element content -->
<button onclick="this.innerHTML = Date()">The time is?</button>

<! -- change this -->
<button onclick="displayDate()">The time is?</button>

<! -- call function -->
<button onclick="displayDate()">The time is?</button>

<script>
function displayDate() {
    document.getElementById("demo").innerHTML = Date();
}
</script>
Event Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page

12.轉義字符

Code Outputs
' single quote
" double quote
\ backslash
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Horizontal Tabulator
\v Vertical Tabulator

13.String Methods

方法 做用
txt.length 返回長度
txt.indexOf("hello") 返回第一次出現hello的index(從0開始)。若是不存在,則返回-1
txt.lastIndexOf("hello") 同上,返回最後一次出現hello的index
txt.search("hello") 相似indexOf,區別是search能夠接受正則,並且不支持第二個參數來定義查找的起始index
txt.slice(start,end) 提取字符串
txt.substring 同上,區別是不能接受負數
txt.substr(start,length) 同slice,區別是第二個參數規定長度
txt.replace("hello", "hi") 把hello替換成hi,默認只替換第一個hello。區分大小寫
txt.replace(/HELLO/i, "hi") 同上,不區分大小寫
txt.toUpperCase() 轉爲大寫
txt.toLowerCase() 轉爲小寫
txt.concat(a,b,c) 在txt字符後再鏈接多個字符,此處a,b,c都是變量
txt.charAt(i) 提取第i個字符,不推薦使用txt[i]的方式,unsafe
txt.charCodeAt(i) 提取第i個字符的unicode
txt.split(",") 以逗號分割字符串成array

14.RegExp 正則表達式

/pattern/modifiers

var str = "Visit Microsoft!";
var res = str.replace(/microsoft/i, "W3Schools");

Modifiers修飾符:

Modifier Description
i 忽略大小寫
g 全局匹配
m 多行匹配

Patterns模型

Patterns Description
[abc] 匹配中括號中的任一字符
[0-9] 匹配任一數字
(x y)
\d 表明一個數字
\s 表明一個空格字符
n+ 表明至少一個n字符
n* 表明0或多個n
n? 表明0或1個n

test():正則表達式方法

patt.test(str):判斷str字符串中是否包含正則表達式patt,返回true或false

exec():正則表達式方法
patt.exec(str):判斷str字符串中是否包含正則表達式patt,若是存在,則返回patt,不然返回null

完整正則參考:https://www.w3schools.com/jsref/jsref_obj_regexp.asp

4、jQuery

1.jQuery: a JavaScript Library
2.Basic syntax:

$(selector).action()

3.jQuery uses CSS syntax to select elements. Examples:

$(this).hide() - hides the current element.

$("p").hide() - hides all <p> elements.

$(".test").hide() - hides all elements with class="test".

$("#test").hide() - hides the element with id="test"

4.ready:等待document徹底加載後,再進行jQuery代碼的執行

$(document).ready(function(){

   // jQuery methods go here...

});

<!-- 爲了簡化寫法,能夠替換成下面的方式 -->
$(function(){

   // jQuery methods go here...

});

5.Selectors

6.functions in s separate file

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script src="my_jquery_functions.js"></script>
</head>

7.syntax for event methods:

click:

$("p").click(function(){
  // action goes here!!
});

double click:

$("p").dblclick(function(){
    $(this).hide();
});

mouse enter:鼠標移到某元素

$("#p1").mouseenter(function(){
    alert("You entered p1!");
});

mouse leave:鼠標離開

$("#p1").mouseleave(function(){
    alert("Bye! You now leave p1!");
});

mousedown()、mouseup()

hover():combination of mouseenter() and mouseleave()

focus:表單的輸入框正在輸入時

$("input").focus(function(){
    $(this).css("background-color", "#cccccc");
});

blur:失去焦點時

8.effects

  • hide()
  • show()
  • toggle():在hide和show之間切換

9.Callback

$("button").click(function(){
$("p").hide("slow", function(){
alert("The paragraph is now hidden");
});
});

例子中hide()方法傳了兩個額外參數,第一個「slow」規定了慢隱藏,第二個則是callback方法,該方法會在動做徹底執行完成後被調用

10.chain鏈式調用

$("#p1").css("color", "red").slideUp(2000).slideDown(2000);

11.jQuery HTML

  • 獲取元素內容
<!--顯示元素內容-->
$("#btn1").click(function(){
    alert("Text: " + $("#test").text());
});

<!--顯示元素內容,包含html標籤-->
$("#btn2").click(function(){
    alert("HTML: " + $("#test").html());
});


<!--顯示錶單元素的內容-->
$("button").click(function(){
    alert("Value: " + $("#test").val());
});

<p>Name: <input type="text" id="test" value="Mickey Mouse"></p>
  • 獲取屬性attributes
$("button").click(function(){
    alert($("#w3s").attr("href"));
});
  • 修改元素內容
$("#btn1").click(function(){
    $("#test1").text("Hello world!");
});
$("#btn2").click(function(){
    $("#test2").html("<b>Hello world!</b>");
});
$("#btn3").click(function(){
    $("#test3").val("Dolly Duck");
});

$("button").click(function(){
    $("#w3s").attr({
        "href" : "https://www.w3schools.com/jquery",
        "title" : "W3Schools jQuery Tutorial"
    });
});
  • 增長元素
append() - Inserts content at the end of the selected elements
prepend() - Inserts content at the beginning of the selected elements
after() - Inserts content after the selected elements
before() - Inserts content before the selected elements
  • 刪除元素
remove() - Removes the selected element (and its child elements)
empty() - Removes the child elements from the selected element

12.jQuery CSS

Methods Description
addClass() Adds one or more classes to the selected elements
removeClass() Removes one or more classes from the selected elements
toggleClass() Toggles between adding/removing classes from the selected elements
css() Sets or returns the style attribute
<!-- 增長class -->
$("button").click(function(){
    $("h1, h2, p").addClass("blue");
    $("div").addClass("important");
});

<!-- 同時增長兩個class:important 和 blue-->
$("button").click(function(){
    $("#div1").addClass("important blue");
});

<!-- 刪除class -->
$("button").click(function(){
    $("h1, h2, p").removeClass("blue");
});

<!-- 獲取css屬性的值 -->
$("p").css("background-color");

<!-- 修改css屬性的值 -->
$("p").css("background-color", "yellow");

<!-- 批量修改多個css屬性的值 -->
$("p").css({"background-color": "yellow", "font-size": "200%"});

13.AJAX

參考:https://www.w3schools.com/jquery/jquery_ref_ajax.asp

AJAX = Asynchronous JavaScript and XML.

In short; AJAX is about loading data in the background and display it on the webpage, without reloading the whole page.

異步加載機制,使得瀏覽器能夠在後端加載數據,而後更新部分頁面,而不須要從新載入整個頁面

  • load
$(selector).load(URL,data,callback);
  • get
$.get(URL,callback);
$("button").click(function(){
    $.get("demo_test.asp", function(data, status){
        alert("Data: " + data + "\nStatus: " + status);
    });
});

callback函數中的第一個參數是請求的內容,第二個參數是請求的狀態。

  • post
$.post(URL,data,callback);
$("button").click(function(){
    $.post("demo_test_post.asp",
    {
        name: "Donald Duck",
        city: "Duckburg"
    },
    function(data, status){
        alert("Data: " + data + "\nStatus: " + status);
    });
});
相關文章
相關標籤/搜索