web front end: Javascript learning notes and jQuery library operations

Posted by sglane on Mon, 10 Jan 2022 21:38:18 +0100

Reading Guide:
JavaScript (JS for short) is a lightweight, interpretive or just in time programming language with function priority. Although it is famous as a scripting language for developing web pages, it is also used in many non browser environments. JavaScript is a dynamic scripting language based on prototype programming and multi paradigm, and supports object-oriented, imperative, declarative and functional programming paradigms. (this article mainly explains web programming)

JavaScript was originally designed by Brendan Eich of Netscape. At first, its scripting language was named LiveScript. Later, Netscape renamed it JavaScript after working with Sun.

characteristic

  • ECMAScript, which describes the syntax and basic objects of the language.
  • Document object model (DOM) describes the methods and interfaces for processing web page content.
  • Browser object model (BOM), which describes the methods and interfaces to interact with the browser

Computer is a very large and wonderful world, and there is no lack of beauty. As a booming existence in recent decades, the growth of web is obvious to all. Therefore, learning web should become a necessary skill, not deep. You can write a management information system and a simple blog website.

I hope you can find your ultimate belonging and your heart.

Post a publicity blog HTML & & CSS (continuously updated)

Javascript

Writing position

// Hanlin Academician
<input type="submit" value="sub" onclick="alert('HelloWorld')">
// Embedded
<script><script>
// External introduction
<script src="xxx.js"><script>

ECMAScript

IO and data types

Input and output statements

// output
console.log(msg)
// Input statement
prompt(info)

Declare variable

var variable_name

data type

  • Simple data types: Number, String, Boolean, Undefined, Null
  • Complex data type: object

Test data type

typeof variable_name

Data type conversion

// Convert to string
variable.toString()
// Convert to number
variable.parseInt()
variable.parseFloat()
// Cast type
Number(variable)
// Convert to Boolean
Boolean(variable)

Operators and Expressions

slightly

Process control

Sequential structure

var a = 1

Branching structure

if () {
	// do something
}
else if () {
	// do something
}
else {
	// do something
}
switch () {
	case 1:
		// do something
	case 2:
		// do something
	default:
		// do something
}

Cyclic structure

for (var i = 0; i < 100; i++) {
	// do something
}
while (i < 100) {
	// do something
}
do while
// Don't look at this

Cycle termination

// Terminate all cycles
break
// Terminate this cycle
continue

array

Create array

var arr = {a, b, c};

Traversal access array

for (var i = 0; i < arr.length; i++) {
	console.log(arr[i])
}

Modify array length

arr.length = 10

function

Define function

function getpwd() {
	// do something
}

Incoming parameters

function getpwd(aru) {
	// do something
}

Return value of function

function getpwd() {
	// do something
	return vari;
}

How functions are declared

// 1
function getpwd() {
	// do something
}
// 2
var f = function getpwd() {
	// do something
}

object-oriented

// Literal creation object
var obj = {
	name: "lh"
	age: 12
	f: function() {
		// do something
	}
}
// new
var obj = new Object();
obj.name = "lh";
obj.age = 10;
obj.f = function() {
	// do something
}
// Constructor
function obj() {
	this.attribute = value;
	this.method = function()
}
new obj();

Traversal object properties

for (variable in obj) {
	// do something
}

Take a look at the js standard library MDN
MDN

Common API

Math,Date,Array

DOM

DOM is an interface that changes the style of web pages

Get element

// Get by ID
document.getElementById()
// According to class
document.getElementsByClassName()
// According to class name
document.getElementsByName()
// According to tag name
document.getElementsByTagName()
// Get body
document.body
// Get HTML
document.documentElement
// Returns the first object according to the specified selector xx, #xx, xx
document.querySelector()
// Returns according to the specified selector
document.querySelectorAll()

// Return as source code
console.log()
// Return as object
console.dir()

event

Trigger response mechanism
Three elements of the event:

  • Event source: event triggered point object, button
  • Event type: how to trigger (onclick) or mouse, keyboard press
  • Event handler: a program assigned by a program
var btn = document.getElementById("click")
btn.onclick = function() {
	alert("Hello World!");
}
Mouse eventTrigger condition
onclickClick the left mouse button to trigger
onmouseoverMouse over trigger
onmouseoutMouse away trigger
onfocusGet mouse focus trigger
onblurLoss of mouse focus trigger
onmousemoveMouse movement trigger
onmouseupMouse bounce trigger
onmousedownMouse press trigger

Modify element content

// From start to end, but HTML tags are removed, and spaces and newlines are removed
element.innerText
// Change everything
element.innerHTML

Modify element attributes

xxx.src = "xxx"

Get element properties

// First kind
console.log(xxx.id);
// Second
var p = querySelector('div');
console.log(p.getAttribute('id'));

set a property

// First kind
p.id = 1;
// Second
p.setAttribute('id', 1);

Remove Attribute

p.removeAttribute('index');

Modify element style

xxx.style.color = "red";

copy node

// Shallow copy, the default is false
var p = ul.children[0].cloneNode();
ul.appendChild(p)
// Deep copy
var p = ul.children[0].cloneNode(true);

Operation table

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <table>
        <thead>
            <tr>
                <th>full name</th>
                <th>operation</th>
                <th>achievement</th>
                <th>subject</th>
            </tr>
        </thead>
        <tbody>

        </tbody>
    </table>
    <script>
        let dates = [
            {
            name: "lh",
            subject: "C++",
            score: "100"
            },
            {
                name: "hl",
                subject: "C++",
                score: "100"
            },
        ];
        let tbody = document.querySelector('tbody');
        for (let i = 0; i < dates.length; i++) {
            let tr = document.createElement('tr');
            tbody.appendChild(tr);
            for (let k in dates[i]) {
                let td = document.createElement('td');
                td.innerHTML = dates[i][k]
                tr.appendChild(td);
            }
            let td = document.createElement('td')
            td.innerHTML = '<a href="javascript:;">delete</a>'
            tr.appendChild(td)
        }
        let as = document.querySelectorAll('a');
        for (let i = 0; i < as.length; i++) {
            as[i].onclick = function () {
                tbody.removeChild(this.parentNode.parentNode)
            }
        }
    </script>
</body>
</html>

BOM

Browser object model is an object that interacts with browser window independently of content and. Its core object is window

Window page loading

window.onload is a window page loading event. When the document content is completely loaded, this event will be triggered (including images, script files, CSS files, etc.), and the processing function will be called.

// First kind
window.onload = function() {}
// Second
window.addEventListener("load", function(){
	// do something
})

1. With window Onload can write the JS code to the top of the page element, because onload is to wait until the page content is loaded,
Then execute the processing function.
2. window.onload the traditional registration event method can only be written once. If there are multiple, it will be written in the last window Onload shall prevail.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Register</title>
	<script type="text/javascript">
		window.addEventListener('load', function() {
			let btn = document.querySelector('button');
			btn.addEventListener('click', function() {
				alert("pp");
			})
		})
	</script>
</head>
<body>
	<button>H</button>
</body>
</html>

Resize window event

window.innerWidth Represents the browser window size
<script type="text/javascript">
	window.addEventListener('resize', function() {
		// do something
	})
</script>

timer

<script type="text/javascript">
	window.setTimeout(function() {
		console.log("A")
	}, 10)
</script>

Stop Timer

window.clearTimeout()

Timing callback timer

setInterval(Callback function, interval milliseconds)
// Clear timer
clearInterval

JS execution mechanism

JS is single threaded
A major feature of JavaScript language is single thread, that is, you can only do one thing at a time. This is because of JavaScript
The mission of this language is that JavaScript is born to deal with user interaction in pages and operate DOM. For example, we are right
You cannot add and delete a DOM element at the same time. You should add before deleting.

  • Synchronization: tasks are executed in sequence
  • Asynchronous: doing multiple things at the same time

The asynchrony of JS is realized through callback function.
-Generally speaking, there are three types of asynchronous tasks:

  • Common events, such as click Resize et al
  • Resource loading, such as load Error et al
  • Timer, including setinterval SetTimeout, etc
    Asynchronous task related callback functions are added to the task queue (also known as message queue).

Implementation mechanism

  • Execute the synchronization task in the stack first.
  • The asynchronous task (callback function) is put into the task queue.
  • -Once all synchronous tasks in the execution stack are executed, the system will read the asynchronous tasks in the task queue in order, and the read asynchronous tasks
    When the service ends waiting, it enters the execution stack and starts execution.

Location object

The window object provides us with a location attribute to get or set the URL of the form, and can be used to resolve the URL. Because this property returns an object, we also call this property location object.

attribute

location object propertiesReturn value
location.hrefGets or sets the entire URL
location. hostReturn to the host (domain name) www.itheima.com com
location.portReturns the port number. If not written, returns an empty string
location.pathnameReturn path
location. searchReturn parameters
location. hashReturning the content # after the clip is common in link anchors

method

location object methodReturn value
location.assign()Like href -, you can jump to a page (also known as a redirect page)
location.replace()Replace the current page, because the history is not recorded, you cannot go back to the page
location.reload()Reload the page, which is equivalent to the refresh button or f5. If the parameter is true, force refresh ctrl+f5

navigator object

The navigator object contains information about the browser. It has many properties. The most commonly used one is userAgent, which can return the value of the user agent header sent by the client to the server.

history object

The window object provides us with a history object to interact with the browser history. This object contains the URL that the user (in the browser window) has visited

history object methodeffect
back()Can reverse function
forward()Forward function
Go (parameter)Forward and backward function parameter if it is 1 forward 1 page if it is - 1 backward 1 page

jQuery

jQuery Library Download

Introducing jQuery

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

Two ways of writing

$
jQuery()

jQuery object and DOM object

  • The object obtained with native JS is the DOM object
  • The element obtained by the jQuery method is the jQuery object.
  • The essence of jQuery object is: the object generated by wrapping DOM object with $(stored in pseudo array form).
// DOM object
var btm = document.querySelector('div');
console.dir(btm);
// jQuery object
$('div')

Mutual transformation:
Converting DOM objects to jQuery objects

var ptr = document.querySelector('id');
$(ptr);

Convert jQuery object to DOM object

// First kind
$('div')[index]
// Second
$('div').get([index])

jQuery selector

Basic and level selectors

$('selector')	// Just write CSS selector directly inside, but use quotation marks
nameusagedescribe
ID Selector $("#id")Gets the element with the specified ID
Select all selector$('*')Match all elements
Class selector $(".class")Get elements of the same class
tag chooser $("div")Gets all elements of the same class of labels
Union selector$("div,p,li")Select multiple elements
Intersection selector$("li.current")Intersection element

Level selector

nameusagedescribe
Progeny selector$("ul>li");Use the > sign to obtain the parent-child level elements; Note that elements at the grandchild level are not obtained
Descendant Selectors $("ul li");Use a space to represent the descendant selector to obtain all li elements under uI, including grandchildren

Implicit iteration

// Get four div
$('div')

The process of traversing internal DOM elements (stored in pseudo array form) is called implicit iteration.

Simple understanding: loop through all the matched elements and execute the corresponding methods instead of us, which simplifies our operation and facilitates our call.

Filter selector

grammarusagedescribe
:first$(li:first')Get the first i element
:last$(li:last')Get last
:eq(index)$("li:eq(2)")Among the obtained i elements, select the element with index number 2, and the index number starts from 0.
:odd$("l:odd")Among the obtained li elements, select the elements with odd index numbers
:even$("li:even")Among the obtained li elements, select the element with an even index number

jQuery filtering method

grammarusageexplain
parent()$("li"). parent();Find parent
children(selector)$("u1"). children("li")Equivalent to $("UL > Li"), the nearest -- level (son)
find(selector)$("ul"). find("li");Equivalent to $("ul li"), descendant selector
siblings(selector)$(". first").siblings("li");Find sibling nodes, excluding itself
nextAll([expr])$(". first"). nextAll()Find all peer elements after the current element
prevtAll([expr])$(" .last"). prevAll()Find all peer elements before the current element
hasClass(class)$('div').hasClass( "protected")Check whether the current element contains a specific class. If so, return true
eq(index)$("li"). eq(2);Equivalent to $("li:eq(2)"), index starts from 0

Case: Sina drop-down menu

$(function() {
	// Mouse passing
	$('.nav>li').mouseover(function() {
		// $(this) jQuery current element
		// show() show element hide() hide element
		$(this).children('ul').show();
	});
	// Mouse away
	$('nav>li').mouseout(function() {
		$(this).children('ul').hide();
	})
})

Exclusive thought
If you want to choose one more effect, exclusive thought: set the style for the current element and clear the style for the other sibling elements.

$(function() {
	// Implicit iteration, binding click events to all buttons
	$("button").click(function() {
		// The current element changes the background color
		$(this).css("background", "pink");
		// The other brothers remove the background color and iterate implicitly
		$(this).siblings("button").css("background", "");
	});
})

jQuery chain programming

Chain programming is to save code and look more elegant.

$(this).css("background", "pink").siblings("button").css("background", "");

jQuery style operation

Manipulating CSS methods
If the parameter only writes the property name, the property value is returned

$(this).css("color");

The parameters are attribute name, attribute value and comma separated. They are set group style. The attribute must be quoted. If the value is a number, it can not be followed by unit and quotation mark

$(this).css("color", "red");

Parameters can be in the form of objects, which is convenient for setting multiple groups of styles. Attribute names and attribute values are separated by colons. Attributes can be separated without quotation marks,

$(this).css({"color": "red", "width": 200});

Add class

<style>
	.current {
		background: red;
	} 
</style>
<div></div>
<script>
	$function() {
		$('div').click(function() {
			$(this).addClass('current');
		})
	}
</script>

Remove class

<script>
	...removeClass();
</script>

Switch class

<script>
	...toggleClass();
</script>

jQuery effect

Show and hide

show();	// display
hide();	// hide
toggle();	// switch

slide

slideUp();	// Pull down sliding
slideDown();	// Drop down hide
slideToggle();	// Pull down sliding

The mouse passes and the mouse leaves

mouseover		// Mouse passing
mouseout	// Mouse away
hover	// Passing and leaving

Fade in and out

fadeIn();		// Fade in
fadeOut();		// Fade out
fadeToggle();	// Fade in and fade out switch
fadeTo();		// Modify transparency and speed

Custom animation

animate(
	params, 	// Style properties you want to modify
	speed, 		// speed
	easing,		// Switching effect
	fn, 		// Callback function
)

jQuery property operation

Get intrinsic properties

// get attribute
prop("index");
// modify attribute
prop("index", 1);		// Inherent properties

Get and set custom properties

attr()

jQuery element content

// Get element content
html()
// Modify element content
html('123');

Get common element text content

text();
text('123');

Get form content

val();
val("asd");

jQuery element operation

jQuery implicit iteration does the same operation on the same element. If you want to do different operations on the same element, you need to use traversal.

// Domelement is a DOM object
$('div').each(function(index, domEle) {
	// do something
	$(domEle).css("color", "red")
})

jQuery size, position and operation

size

grammarusage
width() / height()Get the width and height of the matching element, and only calculate width 1 height
innerWidth()/ innerHieght()Gets the width and height of the matching element, including padding
outerWidth() / outerHeight()Get the width and height values of matching elements, including padding and border
outerWidth(true) / outerHeight(true)Get the width and height values of matching elements, including padding, borde r and margin

position

offset() sets or gets the element offset

  • The offset() method sets or returns the offset coordinates of the selected element relative to the document, which has nothing to do with the parent.
  • This access method has two attributes: left and top. offset).top is used to obtain the distance from the top of the document (offset) Left is used to get the distance to the left of the document.
  • You can set the offset of the element: offset ({top: 10, left: 30});

Position (get element offset)

  • The position() method is used to return the offset coordinates of the selected element relative to the parent with positioning. If the parent has no positioning, the document shall prevail.

jQuery auto trigger event

// First kind
click()
// Second
trigger('click')
// Third
on('foucs', function() {});

Topics: Javascript Front-end html css