[Notes] Crazy God js video notes 09 (final chapter, jQuery)

Related pages ↓

9、jQuery

9.1. What is JQuery

You may have heard of jQuery, which has a silly name but is the most widely used library in the JavaScript world.

Rumor has it that about 80 to 90% of websites around the world use jQuery directly or indirectly. Since it is so popular and so easy to use, every front-end engineer who is getting started with JavaScript should understand and learn it.
jQuery is so popular because it solves some very important problems. In fact, jQuery can help us do these things:

  • Eliminate browser differences: You don’t need to write lengthy code to bind events for different browsers, write AJAX and other codes;
  • A concise way to operate DOM: writing $(’#test’) is definitely more concise than document.getElementById(‘test’);
  • Easily implement various operations such as animation and modifying CSS.

jQuery's concept of "Write Less, Do More" allows you to write less code and complete more work!

官网:https://jquery.com/
文档:https://jquery.cuishifeng.cn/

jQuery is just a jquery-xxx.js file, but you will see that there are two versions: compressed (compressed) and uncompressed (uncompressed), which are exactly the same when used, but if you want to delve into the jQuery source code, use the uncompressed version .

To use jQuery, you only need to introduce the jQuery file in head of the page:

<html>

<head>
    <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
    ...
</head>

<body>
    <a id="test-link" href="#0">点我试试</a>
    <script>
        // 获取超链接的jQuery对象:
        var a = $('#test-link');
        a.on('click', function () {
     
     
            alert('Hello!');
        });

        // 方式二
        a.click(function () {
     
     
            alert('Hello!');
        });
    </script>
</body>

</html>

official:$(selector).action()

  • Dollar sign definition jQuery
  • Selector "Query" and "Find" HTML elements
  • jQuery's action() performs operations on elements

9.2. Selector

The selector is the core of jQuery.
Why did jQuery invent the selector? Let’s review the codes we often use in DOM operations:

// 按ID查找:
var a = document.getElementById('dom-id');
// 按tag查找:
var divs = document.getElementsByTagName('div');
// 查找<p class="red">:
var ps = document.getElementsByTagName('p');
// 过滤出class="red":
// TODO:
// 查找<table class="green">里面的所有<tr>:
var table = ...
for (var i=0; i<table.children; i++) {
    
    
// TODO: 过滤出<tr>
}

This code is too cumbersome!
jQuery’s selector helps us quickly locate one or more DOM nodes.

Find by ID

If a DOM node has the id attribute, use jQuery to search as follows:

// 查找<div id="abc">:
var div = $('#abc');

Search by tag

To search by tag, just write the tag name:

var ps = $('p'); // 返回所有<p>节点
ps.length; // 数一数页面有多少个<p>节点

Search by class

Search by class, please add one before the class name .:

var a = $('.red'); // 所有节点包含`class="red"`都将返回
// 例如:
// <div class="red">...</div>
// <p class="green red">...</p>

Search by attributes
A DOM node can have many attributes in addition to id and class. In many cases, press Attribute search is very convenient, for example, searching by attribute in a form:

var email = $('[name=email]'); // 找出<??? name="email">
var passwordInput = $('[type=password]'); // 找出<??? type="password">
var a = $('[items="A B"]'); // 找出<??? items="A B">

When the value of an attribute contains special characters such as spaces, it needs to be enclosed in double quotes.
To search by attribute, you can also use prefix search or suffix search:

var icons = $('[name^=icon]'); // 找出所有name属性值以icon开头的DOM
// 例如: name="icon-1", name="icon-2"
var names = $('[name$=with]'); // 找出所有name属性值以with结尾的DOM
// 例如: name="startswith", name="endswith"

9.3. Manipulating DOM

Modify Text and HTML

text()The and html() methods of the jQuery object obtain the text of the node and the original HTML text respectively. For example, the following HTML structure:

<!-- HTML结构 -->
<ul id="test-ul">
    <li class="js">JavaScript</li>
    <li name="book">Java &amp; JavaScript</li>
</ul>

Get text and HTML separately:

$('#test-ul li[name=book]').text(); // 'Java & JavaScript'
$('#test-ul li[name=book]').html(); // 'Java &amp; JavaScript'

How to set text or HTML? The API design of jQuery is very clever: calling text() without parameters is to get text, and passing in parameters becomes setting text. HTML is also a similar operation. Try it yourself:

var j1 = $('#test-ul li.js');
var j2 = $('#test-ul li[name=book]');
j1.html('<span style="color: red">JavaScript</span>');
j2.text('JavaScript & ECMAScript');

A jQuery object can contain 0 or any number of DOM objects, and its methods will actually act on each corresponding DOM node. Try this in the example above:

$('#test-ul li').text('JS'); // 是不是两个节点都变成了JS?

Modify CSS

jQuery objects have the feature of "batch operations", which is very convenient for modifying CSS. Consider the following HTML structure:

<!-- HTML结构 -->
<ul id="test-css">
    <li class="lang dy"><span>JavaScript</span></li>
    <li class="lang"><span>Java</span></li>
    <li class="lang dy"><span>Python</span></li>
    <li class="lang"><span>Swift</span></li>
    <li class="lang dy"><span>Scheme</span></li>
</ul>

To highlight dynamic languages, call the css(‘name’, ‘value’) method of the jQuery object. We implement this with a single line:

$('#test-css li.dy>span').css('background-color', '#ffd351').css('color','red');

Note that all methods of the jQuery object return a jQuery object (which may be a new one or itself), so that we can make chain calls, which is very convenient.

The css() method of the jQuery object can be used like this:

var div = $('#test-div');
div.css('color'); // '#000033', 获取CSS属性
div.css('color', '#336699'); // 设置CSS属性
div.css('color', ''); // 清除CSS属性

css()The method will act on the style attribute of the DOM node, with the highest priority. If you want to modify the class attribute, you can use the following methods provided by jQuery:

var div = $('#test-div');
div.hasClass('highlight'); // false, class是否包含highlight
div.addClass('highlight'); // 添加highlight这个class
div.removeClass('highlight'); // 删除highlight这个class

Show and hide DOM

To hide a DOM, we can set the CSS display attribute to none and use the css() method to achieve this .

However, to display this DOM, you need to restore the original display attribute. In this case, you must first write down what the original display attribute is. /span> attribute, in short it can work normally: methods, we don’t need to care how it works Modify and Considering that showing and hiding DOM elements is very common, jQuery directly provides or another value. block or inline
show()hide()display

var a = $('a[target=_blank]');
a.hide(); // 隐藏
a.show(); // 显示

Note that hiding DOM nodes does not change the structure of the DOM tree, it only affects the display of DOM nodes. This is different from deleting DOM nodes.

Get DOM information

Using several methods of the jQuery object, we can directly obtain information such as the height and width of the DOM without writing specific code for different browsers:

// 浏览器可视窗口大小:
$(window).width(); // 800
$(window).height(); // 600

// HTML文档大小:
$(document).width(); // 800
$(document).height(); // 3500

// 某个div的大小:
var div = $('#test-div');
div.width(); // 600
div.height(); // 300
div.width(400); // 设置CSS属性 width: 400px,是否生效要看CSS是否有效
div.height('200px'); // 设置CSS属性 height: 200px,是否生效要看CSS是否有效

attr()The and removeAttr() methods are used to operate the attributes of DOM nodes:

// <div id="test-div" name="Test" start="1">...</div>
var div = $('#test-div');
div.attr('data'); // undefined, 属性不存在
div.attr('name'); // 'Test'
div.attr('name', 'Hello'); // div的name属性变为'Hello'
div.removeAttr('name'); // 删除name属性
div.attr('name'); // undefined

Operation form

For form elements, jQuery objects uniformly provide val() methods to get and set the corresponding value attributes:

/*
<input id="test-input" name="email" value="">
<select id="test-select" name="city">
    <option value="BJ" selected>Beijing</option>
    <option value="SH">Shanghai</option>
    <option value="SZ">Shenzhen</option>
</select>
<textarea id="test-textarea">Hello</textarea>
*/
var
    input = $('#test-input'),
    select = $('#test-select'),
    textarea = $('#test-textarea');
    
input.val(); // 'test'
input.val('[email protected]'); // 文本框的内容已变为[email protected]

select.val(); // 'BJ'
select.val('SH'); // 选择框已变为Shanghai

textarea.val(); // 'Hello'
textarea.val('Hi'); // 文本区域已更新为'Hi'

It can be seen that one val() unifies the problem of value acquisition and assignment of various input boxes.

Add DOM

To add a new DOM node, in addition to the violent method of jQuery's html(), you can also use the append() method, for example:

<div id="test-div">
	<ul>
		<li><span>JavaScript</span></li>
		<li><span>Python</span></li>
		<li><span>Swift</span></li>
	</ul>
</div>

How do I add a new language to the list? First we need to get the <ul> node:

var ul = $('#test-div>ul');

Then, call append() passing in the HTML fragment

ul.append('<li><span>Haskell</span></li>');

append() adds the DOM to the end, prepend() adds the DOM to the front.

If you want to insert a new node into a specified position, for example, between JavaScript and Python, you can first locate JavaScript and then use the after() method:

var js = $('#test-div>ul>li:first-child');
js.after('<li><span>Lua</span></li>');

In other words, peer nodes can use the after() or before() method.

Delete node

To delete the DOM node, just call the remove() method directly after getting the jQuery object. If the jQuery object contains several DOM nodes, you can actually delete multiple DOM nodes at once:

var li = $('#test-div>ul>li');
li.remove(); // 所有<li>全被删除

9.4. Events

The events that jQuery can bind mainly include:

mouse events

  • click: triggered when the mouse clicks;
  • dblclick: Triggered when the mouse is double-clicked;
  • mouseenter: triggered when the mouse enters;
  • mouseleave: triggered when the mouse moves out;
  • mousemove: triggered when the mouse moves inside the DOM;
  • hover: Two functions are triggered when the mouse enters and exits, equivalent to mouseenter plus mouseleave.

Keyboard events

Keyboard events only act on the currently focused DOM.
keydown: triggered when the keyboard is pressed;
keyup: triggered when the keyboard is released;
keypress: triggered after pressing the key once .

Other events

focus: triggered when the DOM gains focus;
blur: triggered when the DOM loses focus;
change: when the value of the element changes , a change event will occur.
submit: When the form is submitted, the submit event occurs.
ready: Triggered when the page is loaded and the DOM tree is initialized.

jQuery API Chinese documentation | jQuery API Chinese online manual | jquery api download | jquery api chm

initialization event

Our own initialization code must be placed in the event of the document object to ensure that the DOM has been initialized: ready

<html>

<head>
    <script>
        $(document).on('ready', function () {
     
     
            $('#testForm').on('submit', function () {
     
     
                alert('submit!');
            });
        });
    </script>
</head>

<body>
    <form id="testForm">
        ...
    </form>
</body>

There is no problem if you write it this way. Because the relevant code will be executed after the DOM tree is initialized.

Since ready events are very common, they can be simplified as follows:

$(document).ready(function () {
    
    
    // on('submit', function)也可以简化:
    $('#testForm').submit(function () {
    
    
        alert('submit!');
    });
});

It can even be simplified to:

$(function () {
    
    
	// init...
});

event parameters

For some events, such as mousemove and keypress, we need to get the values ​​of the mouse position and keystrokes, otherwise there is no point in listening to these events. All events will be passed in the Event object as a parameter, and more information can be obtained from the Event object:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #testMouseMoveDiv {
     
     
            width: 300px;
            height: 300px;
            border: 1px solid black;
        }
    </style>
</head>

<body>
    mousemove: <span id="testMouseMoveSpan"></span>
    <div id="testMouseMoveDiv">
        在此区域移动鼠标试试
    </div>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
    <script>
        $(function () {
     
     
            $('#testMouseMoveDiv').mousemove(function (e) {
     
     
                $('#testMouseMoveSpan').text('pageX = ' + e.pageX + ', pageY = ' +
                    e.pageY);
            });
        });
    </script>
</body>

</html>

Guess you like

Origin blog.csdn.net/lj22377/article/details/113090162