Quick Introduction to jQuery Basics Part 2

jQueryAdvanced


event bubbling

What is event bubbling?

        A certain type of event is triggered on an object, and the event handler is defined on the object, then the event will call the handler, if the event handler is not defined or the event returns true, then the event will be sent to the object The parent object propagates, from inside to outside, until it is processed, or reaches the topmost level of the object hierarchy, the document object;

Event bubbling?

        Event bubbling allows multiple operations to be handled centrally (adding event handlers to one parent element, avoiding adding event handlers to multiple child elements), it also allows you to capture events at different levels of the object layer .

Prevent event bubbling?

        The bubbling of events is sometimes unnecessary and redundant, and needs to be stopped by event.stopPropagation()

// 外层box1 里层box2
$(function(){    
    var $obox1 = $('.box1')
    var $obox2 = $('.box2')
    $obox1.click(function(){console.log(1)});
    $obox2.click(function(){console.log(2)});
})
// 冒泡结果 2 1
// 阻止冒泡
$obox2.click(function(event){ event.stopPropagation(); console.log(2); })

 Merge blocking operations?

// 阻止冒泡
event.stopPropagation()
// 阻止默认行为
event.preventDefault()

// 合并写法
return false

$obox2.click(function(event){ 
    // event.stopPropagation();
    console.log(2);
    return false
})

Case - pop-up window

        To complete the effect of the picture below, the pop-up window is closed by default at first, and the pop-up window is opened by controlling the button, and the middle body and the outer mask layer will appear. Click the mask layer to close the pop-up window, or through Manually close the button to close the pop-up window. Clicking on the main body range in the middle will not trigger the closing of the pop-up window, because this pop-up window may need to do other operations, such as clicking the update button, or submitting some other information, so the content of the main body Bubbling is required.

 [ Xiaobai's analysis idea : first add a click event to the button to control the display and hiding of the pop-up window, and set a click event for the close button. The methods of hiding and displaying can use hide() and show() 

$('#btn').click(function(){ $('#main').show() })
$('#close').click(function(){ $('#main').hide() })

The external mask layer can use this document object

$(document).click(function(){ $('#main').hide() })

Using this method, you will find a problem with it. There is no response after clicking. It is not that there is no response here, but it is too fast! After clicking the input button, it will bubble to the body, so from the beginning hide() - show() - hide(): test it with a timer:

// 测试 :input冒泡 —— body —— document 
$(document).click(function(){ 
    setTimeout(function(){
        $('#main').hide() 
    },2000)
})

So what needs to be done here is to prevent a bubbling behavior of the event;

The content of the main body is the content of this class = "content". When the mouse clicks on the scope of the main content, this bubbling will occur. From this content to class = "main" ... bubbling outward, so it is necessary to prevent class="content "The act of bubbling outward.

$('.content').click(function(){ return false })

Finally, place the overall code below, and write the style yourself!

<body>
    <input type="button" value="弹窗" id="btn"/>

    <div class="main" id="main">
        <div class="content">
            <div class="cTitle">
                <h3>更新提示</h3>
                <a href="" id="close"> x </a>
            </div>
            <div class="cDetail">
                <p>
                    <span> >· 软件应用版本可更新 V 1.2.0</span>
                    <ul>
                        <li><a href="">自动更新 -></a></li>
                        <li><a href="">手动更新 -></a></li>
                    </ul> 
                </p>
            </div>
        </div>
    </div>

    <script>   
        // 阻止事件的冒泡即可
        $('#btn').click(function(){ $('#main').show();return false; })
        $('#close').click(function(){ $('#main').hide() })
        // 点击弹框
        $(document).click(function(){ $('#main').hide() })
        // $('.content').click(function(event){ event.stopPropagation() })
        $('.content').click(function(){ return false })
    </script>
</body>

event delegation

        Event delegation is to use the principle of bubbling to bind the event to the parent, and the events that occur in the subset will bubble to the parent, and the parent will give it specific operations by judging the characteristics of the child. First of all, event delegation can greatly reduce the number of event bindings and improve performance; secondly, it can allow newly added sub-elements to have the same operations.

// 一般写法
$(function(){
    $li = $('#list li');
    $li.click(function(){
        $(this).css({ color:'red' })
    })
})


<ul id="list">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
</ul>

        The performance of event delegation is better;

// 事件委托
$ul = $('#list');
$ul.delegate('li','click',function(){
    $(this).css({ color:'red' })
})

 DOM manipulation

Element node operation refers to changing the label structure of html, which has two situations:

        1. Move the position of the existing label

        2. Insert the newly created label into the existing label

create new label

var $div = $('<div>')     // 创建一个空div
var $div = $('<div>这是一个div元素</div>')

How to Move or Insert Tabs

1. append() and appendTo(), in the content of the existing element, put the element from the back

<div id="obox"></div>

var $span = $('<span>这是一个span元素</span>')
$('#obox').append($span)
$span.appendTo('#obox')

 2. 2. prepend() and prependTo, in the content of the existing element, put the element from the front

 

 3. after() and insertAfter(), in the content of the existing element, insert the element from the back

4. before() and insertBefore(), in the content of the existing element, insert the element from the front

 5. remove() removes the tag

// remove() 删除标签
$('#obox').remove()

Case - To Do

 [Analysis of Xiaobai's thinking: This case must be familiar to many people. An example similar to a to-do memo mainly uses the input box to obtain the input data ( val() ), and triggers the click event ( click ) by adding a button. Insert the content and template content to the corresponding node ( append() ), and at the same time, perform DOM operations on the inserted node, delete up and down operations, and the animation of the deletion operation is to move to the right and gradually disappear and be deleted ( animate() ), the animation in the previous article mentioned that it can be combined and reviewed, and the corresponding up and down icons here use font-awesome]

Attached address: Font Awesome, a set of excellent icon font library and CSS framework

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha512-SfTiTlX6kk+qitfevl/7LibUOeJWlt9rbyDn92a1DqWOw9vWG2MFoays0sgObmWazO5BQPiFucnnEAjpAB+/Sw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <script src="./jquery-3.6.4.min.js"></script>
    <style> /* 自行编写 */ </style>
</head>
<body>
    <div class="content">
        <h2>List 待办 | To do</h2>
        <input type="text" id="inText" class="inTxt"/>
        <input type="button" value="添加" id="btn" class="addbtn"/>
        
        <ul id="list">
            <li>
                <span class="addText">记录今天有趣的待办事情吧!</span>
                <a href="javascript:;" id="del" class="del">删除</a>
                <a href="javascript:;" id="up" class="up"><i class="fa fa-long-arrow-up"></i></a>
                <a href="javascript:;" id="down" class="down"><i class="fa fa-long-arrow-down"></i></a>
            </li>
        </ul>
    </div>

    <script>
        $(function(){
            var $inText = $('#inText')  
            var $addbtn = $('#btn')
            var $del = $('#del')
            var $list = $('#list')

            // 添加事件
            $addbtn.click(function(){
                var $inVal = $inText.val() 
                if($inVal == ''){
                    alert('请先输入内容..')
                    return 
                }

                // 节点模板
                var $li = $('<li><span class="addText">' + $inVal
                    + '</span><a href="javascript:;" class="del" >删除</a><a href="javascript:;" class="up"><i class="fa fa-long-arrow-up"></i></a><a href="javascript:;" class="down"><i class="fa fa-long-arrow-down"></i></a></li>')
                    
                // 插入节点
                var $list = $('#list')
                $list.append($li)

                // 清空输入框
                $inText.val('') 
            })

            // 删除事件 - 性能低
            // $del.click(function(){
            //     // $(this).parent().remove()
            //     $(this).remove()
            // })

            // 事件委托代理
            $list.delegate('a','click',function(){
                // 判断所选操作:删除 上 下
                var $cVal = $(this).prop('class');
                // 删除
                if($cVal == 'del'){
                    // 动画效果
                    $(this).parent().animate({left:'200px',opacity:'0'},500,'linear',function(){
                        // $(this).parent.remove()
                        $(this).remove()
                    })
                }
                // 上移
                if($cVal == 'up'){
                    // prev() 找到每个段落紧邻的前一个同辈元素
                    $(this).parent().insertBefore($(this).parent().prev())
                }
                // 下移
                if($cVal == 'down'){
                    // insertAfter()
                    $(this).parent().insertAfter($(this).parent().next())
                }
            })
        })
    </script>
</body>
</html>

Ajax

Partial refresh and asynchronous refresh

        Ajax can achieve partial refresh, also known as no refresh. No refresh means that the page does not refresh as a whole, but only partial refresh. Ajax can send http data requests by itself without going through the url address bar of the browser, so the page as a whole will not Refresh, ajax obtains background data, updates the part of the page displaying data, and achieves a partial refresh of the page

ajax request

$.ajax usage method, parameters

url         请求地址
type        请求方式,默认是'GET',常用的还有'POST'
dataType    设置返回数据的格式,常用的是'json'格式 
data        设置发送给服务器的数据
success     请求成功后的回调函数
error       请求失败后的回调函数
async       设置是否异步,默认true,表同步

1) the past way of writing

$.ajax({
    url:'/api/swiperList',
    type:'GET',
    dataType:'json',
    data:{ 'code':0 }
    success:function(data){
        alert(data);
    }
    error:function(err){
        alert(err);
    }
})

2) Recommended new writing method

$.ajax({
    url:'/api/swiperList',
    type:'GET',
    dataType:'json',
    data:{ 'code':0 }
})
.done(function(data){
    alert(data)
})
.fail(function(err){
    alert(err)
})

        Here to test it, you need to use the structure of the test data, here you can take a look Wechat applet equipped with node.js server

The test interface server equipped with it is relatively simple and easy to use. Let's use it to test the $.ajax() request:

<div id="msg"></div>
<script>
    $.ajax({
        url:'http://127.0.0.1:3000/api/swiperList',
        method:'GET',
        dataType:'json',
        // success:function(data){
        //     console.log(data)
        // },
        // error:function(err){
        //     console.log(err)
        // }
    })
    .done(function(data){ console.log(data);$('#msg').html('<p>' + data.data.swiperList[0].imgUrl + '</p>') })
    .fail(function(err){ console.log(err) })
</script>


read file

        Ajax reads the txt file and displays the read content on the page. Create such an interface on the Node.js server, read the test.txt file in the public, and return the read content to the client.

test.txt file content

这是一个测试文本

        The interface test can get the data, which is read and displayed on the page through ajax:

<div id="msg"></div>
<script>
    $.ajax({
        url:'http://127.0.0.1:3000/test.txt',
        method:'GET',
        dataType:'text',
    })
    .done(function(data){ 
        console.log(data);
        // 插入节点
        $('#msg').html('<p>' + data + '</p>')
    })
    .fail(function(err){ console.log(err) })
</script>


 read json data

        Ajax reads the json file and displays the read file on the page.

test.json

{
    "name":"syan",
    "age":"18"
}

        The interface test can get the data, which is read and displayed on the page through ajax:

<div id="msg"></div>
<script>
    $.ajax({
        url:'http://127.0.0.1:3000/test.json',
        method:'GET',
        dataType:'json',
    })
    .done(function(data){ 
        console.log(data);
        // 插入节点
        var arr = data
        var temp = ''
        for(var i = 0;i<arr.length;i++){
            console.log(arr[i].name,arr[i].age)
            temp += '姓名:' + arr[i].name + ',年龄:' + arr[i].age + '<br>'
        }
        $('#msg').html(temp)
    })
    .fail(function(err){ console.log(err) })
</script>

         This concludes the content of this article, thank you for your support! ! ! A link to the previous article is attached, and interested readers can go to read it.

AttachmentThe first part of jQuery Basics Quick Start

Guess you like

Origin blog.csdn.net/weixin_52203618/article/details/130041316