The third day of jQuery study

Posted by endlyss on Thu, 03 Mar 2022 15:03:47 +0100

The third day of jQuery study

1. Event registration

  • grammar
element.event(function(){})
  • for example
$("div").click(function(){})

2. jQuery event handling

2.1 event handling on() binding event

  • grammar
element.on(events,[selector],[data],fn)
  • Events: trigger events, separated by commas

  • Selector: select descendants of selector elements

  • date: event object passed to fn

  • fn: event handler

2.1.1 binding multiple events

$("div").on({
     mouseover: function(){}, 
    mouseout: function(){},
    click: function(){}
}); 

2.1.2 multiple events, same handler

$("div").on("mouseover mouseout", function() {
     $(this).toggleClass("current");
 }); 

Example

<!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>
    <script src="./jquery.min.js"></script>
    <style>
        div {
            height: 200px;
            width: 200px;
            background-color: pink;
        }
        
        .current {
            background-color: blue;
        }
    </style>
</head>

<body>
    <div class="one"></div>
    <div class="two"></div>
    <script>
        $(function() {
            // 1. Event binding, binding multiple events

            $(".one").on({
                click: function() {
                    $(this).css({
                        "backgroundColor": "skyblue"
                    })
                },

                "mouseout mouseover": function() {
                    $(this).toggleClass("current");
                }

            })

            // Multiple events, one callback function
            $(".two").on({
                "mouseout mouseover": function() {
                    $(this).toggleClass("current");
                }
            })


        })
    </script>
</body>

</html>
  • design sketch

2.2 event delegation

  • Use on to handle events, bind events to the parent element, the child element is used as the trigger event source, and the events of the child element bubble to the parent element
  • Use the selector parameter: the event source of the triggered child
Example
<!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>
    <style>

    </style>
    <script src="./jquery.min.js"></script>
</head>

<body>
    <ul>
        <li>I am a li label</li>
        <li>I am a li label</li>
        <li>I am a li label</li>
        <li>I am a li label</li>
        <li>I am a li label</li>
    </ul>

    <script>
        $(function() {
            // 1. Bind an event to the parent element, and the child element is the source of the child contact. Bubble: event delegation

            $("ul").on("click", "li", function(e) {
                // alert("pop-up box");
                // $(this) is the trigger source li, not the ul of the bound event
                console.log($(this));

                $(this).css({
                    color: "red"
                })
            })
        })
    </script>
</body>

</html>
  • design sketch

2.3 dynamic binding events

  • Example
<!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>
    <script src="./jquery.min.js"></script>
</head>

<body>
    <ol>

    </ol>

    <script>
        $(function() {
            // 1. The elements created later can also bind events

            // 1. General method

            // $("ol li").click(function() {
            //     alert(111);
            // })

            // 2. For the on event method, li needs to be written on the trigger source

            // $("ol li").on({
            //     "click": function() {
            //         alert(111);
            //     }
            // })

            $("ol").on("click", "li", function() {
                alert(111)
            })

            var li1 = $("<li>I am a li label</li>");

            $("ol").append(li1);
        })
    </script>
</body>

</html>
  • Effect drawing of common method

  • on method dynamic binding

Post message case

<!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>
    <style>
        li {
            width: 600px;
            height: 30px;
            background-color: pink;
            line-height: 30px;
            padding: 3px;
            margin: 10px;
        }
        
        a {
            float: right;
        }
    </style>
    <script src="./jquery.min.js"></script>
</head>

<body>
    <input type="text" placeholder="Please enter a message"><button>release</button>
    <ul>

    </ul>

    <script>
        $("button").on("click", function() {
            if ($("input").val() == "") {
                alert("Input cannot be empty");
            } else {
                // Add li tag
                var li = $("<li>" + $("input").val() + "<a href='#'> delete < / a > < / Li > ");
                $("ul").prepend(li);
            }
        })

        // Dynamic binding event
        $("ul").on("click", "li a", function() {
            $(this).parent("li").remove();
        })
    </script>
</body>

</html>
  • design sketch

2.4 off event

  • The off() method removes the event handler added through the on () method

  • Unbind all events

$("div").off()
  • Unbind an event
$("p").off("click")
  • Unbinding event delegation
$("ul").off("click","li")

Example

<!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>
    <script src="./jquery.min.js"></script>
    <style>
        div {
            width: 200px;
            height: 200px;
            background-color: pink;
            margin-bottom: 20px;
        }
    </style>
</head>

<body>
    <div class="one"></div>
    <div class="two"></div>
    <ul>
        <li>I am a li label</li>
        <li>I am a li label</li>
        <li>I am a li label</li>
        <li>I am a li label</li>
        <li>I am a li label</li>
    </ul>

    <script>
        $(function() {
            // First div binding event
            $(".one").on({
                    click: function() {
                        console.log("one It was clicked");
                    },

                    mouseover: function() {
                        console.log("Mouse in one in");
                    }
                })
                // The second div binding event
            $(".two").on({
                    click: function() {
                        console.log("two It was clicked");
                    },

                    mouseover: function() {
                        console.log("Mouse in two in");
                    }
                })
                // Event delegation
            $("ul").on("click", "li", function() {
                alert("Spring frame");
            })

            // Remove all event bindings for the first div

            $(".one").off();

            // Remove an event binding from the second div tag

            $(".two").off("mouseover");

            // Remove ul's event delegate

            $("ul").off("click", "li");
        })
    </script>
</body>

</html>
  • design sketch

The one binding event is triggered only once, but not later

<!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>
    <script src="./jquery.min.js"></script>
</head>

<body>
    <div>I am a div</div>
    <script>
        $(function() {
            // one binding event, triggered only once

            $("div").one("click", function() {
                alert("one");
            })
        })
    </script>
</body>

</html>
  • design sketch

2.5 automatic triggering event

  • Element Event () triggers the default behavior
element.click()
  • Element trigger("event type") triggers the default behavior
element.trigger("type")
  • Element Trigger handler ("event type") does not trigger the default behavior
element.triggerHander("focus")

Example

<!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>
    <script src="./jquery.min.js"></script>
</head>

<body>
    <input type="text">
    <script>
        $(function() {

            // Binding event
            $("input").on("focus", function() {

                    $(this).val("hello");
                })
                //  1.element.focus(), / / the cursor flashes after the value changes
                // $("input").focus();

            // 2.element.trigger(type) also flashes after the value changes

            $("input").trigger("focus");

            // 3.element. Trigger handle (type) to prevent default behavior (cursor blinking)
            // $("input").triggerHandler("focus");


        })
    </script>
</body>

</html>
  • Have default behavior

  • No default behavior

3.jQuery event object

  • When an event is triggered, there will be an event object

Example

<!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>
    <script src="./jquery.min.js"></script>
    <style>
        div {
            width: 200px;
            height: 200px;
            background-color: pink;
        }
    </style>
</head>

<body>
    <div></div>
    <script>
        $(function() {
            // Event Bubbling 

            $(document).on("click", function() {
                console.log("Click doc");
            })

            $("div").on("click", function(e) {
                console.log(e);
                console.log("Click div");

                // Stop bubbling

                e.stopPropagation();
            })
        })
    </script>
</body>

</html>
  • Bubble effect drawing

  • Effect drawing of preventing bubbling

4. jQuery copy object

  • Copy (merge) an object to another object

  • grammar

$.extend([deep],target,object1,[objectN])
  1. Deep copy: set to true if deep copy is set to false
  2. Target: target object copied to
  3. object1: object to be copied to
  4. objectN: object N to be copied to the target object
  5. Shallow copy is the copy address when copying complex data types
  6. Deep copy is a copy object when copying a data type

Example

<!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>
    <script src="./jquery.min.js"></script>
</head>

<body>
    <script>
        $(function() {

            var target = {
                name: 200,
            };

            var target1 = {
                name: 200,
                msg: {
                    id: 100
                }
            }

            var object1 = {
                name: 18,
                age: 11,
                msg: {
                    address: "666"
                }
            };

            // Shallow copy

            $.extend(target, object1);

            console.log(target);
            console.log(object1);


            // Deep copy

            $.extend(true, target1, object1);

            console.log(target1);
            console.log(object1);




        })
    </script>
</body>

</html>
  • design sketch

Note: the difference between deep copy and shallow copy

5. Multi database coexistence

  • Problem description

    • jQuery usage do by mark show symbol , along with means j Q u e r y of flow that 's ok , his he j s library also meeting use this individual As an identifier, with the popularity of jQuery, other js libraries will also use this As an identifier, with the popularity of jQuery, other js libraries will also use this as an identifier, which will cause conflicts when used together
  • Solution

    • Change the $symbol inside to jQuery
    • The jQuery variable specifies a new name: $ noConflict()
    var xx=$.noConflict()
    

Example

<!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>
    <script src="./jquery.min.js"></script>
</head>

<body>
    <div></div>
    <script>
        // For example, for another library, use $as the function name

        function $(ele) {
            return document.querySelector(ele);
        }

        // When using $(jQuery method, an error will be reported)

        // $.each();

        // 1. Change solution 1 to jQuery identifier
        // jQuery.each();

        // Solution 2: user defined identifier

        var newName = jQuery.noConflict();

        console.log(newName("div"));
    </script>
</body>

</html>
  • Conflict rendering

  • The first method

  • The second method

6.jQuery plug-in

6.1 waterfall plug-in

  • Download address

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="css/normalize.css">
    <link rel="stylesheet" type="text/css" href="css/default.css">
    <style type="text/css">
        #gallery-wrapper {
            position: relative;
            max-width: 75%;
            width: 75%;
            margin: 50px auto;
        }
        
        img.thumb {
            width: 100%;
            max-width: 100%;
            height: auto;
        }
        
        .white-panel {
            position: absolute;
            background: white;
            border-radius: 5px;
            box-shadow: 0px 1px 2px rgba(0, 0, 0, 0.3);
            padding: 10px;
        }
        
        .white-panel h1 {
            font-size: 1em;
        }
        
        .white-panel h1 a {
            color: #A92733;
        }
        
        .white-panel:hover {
            box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.5);
            margin-top: -5px;
            -webkit-transition: all 0.3s ease-in-out;
            -moz-transition: all 0.3s ease-in-out;
            -o-transition: all 0.3s ease-in-out;
            transition: all 0.3s ease-in-out;
        }
    </style>

</head>

<body>
    <section id="gallery-wrapper">
        <article class="white-panel">
            <img src="images/P_000(1).jpg" class="thumb">
            <h1><a href="#"> I'm rotating picture 1</a></h1>
            <p>It's wonderful inside</p>
        </article>
        <article class="white-panel">
            <img src="images/P_001.jpg" class="thumb">
            <h1><a href="#">Title 1</a></h1>
            <p>Description 1</p>
        </article>
        <article class="white-panel">
            <img src="images/P_002.jpg" class="thumb">
            <h1><a href="#">Title 1</a></h1>
            <p>Description 1</p>
        </article>
        <article class="white-panel">
            <img src="images/P_003.jpg" class="thumb">
            <h1><a href="#">Title 1</a></h1>
            <p>Description 1</p>
        </article>
        <article class="white-panel">
            <img src="images/P_004.jpg" class="thumb">
            <h1><a href="#">Title 1</a></h1>
            <p>Description 1</p>
        </article>
        <article class="white-panel">
            <img src="images/P_005.jpg" class="thumb">
            <h1><a href="#"> I'm rotating picture 1</a></h1>
            <p>It's wonderful inside</p>
        </article>
        <article class="white-panel">
            <img src="images/P_006.jpg" class="thumb">
            <h1><a href="#"> I'm rotating picture 1</a></h1>
            <p>It's wonderful inside</p>
        </article>
        <article class="white-panel">
            <img src="images/P_007.jpg" class="thumb">
            <h1><a href="#"> I'm rotating picture 1</a></h1>
            <p>It's wonderful inside</p>
        </article>
    </section>

    <script src="js/jquery-1.11.0.min.js"></script>
    <script src="js/pinterest_grid.js"></script>
    <script type="text/javascript">
        $(function() {
            $("#gallery-wrapper").pinterest_grid({
                no_columns: 3,
                padding_x: 15,
                padding_y: 10,
                margin_bottom: 50,
                single_column_breakpoint: 700
            });

        });
    </script>

</body>

</html>
  • design sketch

6.2 image loading plug-in

  • Download address

  • design sketch

7. A comprehensive case

  • Copy todolist

  • css file

body {
    margin: 0;
    padding: 0;
    font-size: 16px;
    background: #CDCDCD;
}

header {
    height: 50px;
    background: #333;
    background: rgba(47, 47, 47, 0.98);
}

section {
    margin: 0 auto;
}

label {
    float: left;
    width: 100px;
    line-height: 50px;
    color: #DDD;
    font-size: 24px;
    cursor: pointer;
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

header input {
    float: right;
    width: 60%;
    height: 24px;
    margin-top: 12px;
    text-indent: 10px;
    border-radius: 5px;
    box-shadow: 0 1px 0 rgba(255, 255, 255, 0.24), 0 1px 6px rgba(0, 0, 0, 0.45) inset;
    border: none
}

input:focus {
    outline-width: 0
}

h2 {
    position: relative;
}

span {
    position: absolute;
    top: 2px;
    right: 5px;
    display: inline-block;
    padding: 0 5px;
    height: 20px;
    border-radius: 20px;
    background: #E6E6FA;
    line-height: 22px;
    text-align: center;
    color: #666;
    font-size: 14px;
}

ol,
ul {
    padding: 0;
    list-style: none;
}

li input {
    position: absolute;
    top: 2px;
    left: 10px;
    width: 22px;
    height: 22px;
    cursor: pointer;
}

p {
    margin: 0;
}

li p input {
    top: 3px;
    left: 40px;
    width: 70%;
    height: 20px;
    line-height: 14px;
    text-indent: 5px;
    font-size: 14px;
}

li {
    height: 32px;
    line-height: 32px;
    background: #fff;
    position: relative;
    margin-bottom: 10px;
    padding: 0 45px;
    border-radius: 3px;
    border-left: 5px solid #629A9C;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.07);
}

ol li {
    cursor: move;
}

ul li {
    border-left: 5px solid #999;
    opacity: 0.5;
}

li a {
    position: absolute;
    top: 2px;
    right: 5px;
    display: inline-block;
    width: 14px;
    height: 12px;
    border-radius: 14px;
    border: 6px double #FFF;
    background: #CCC;
    line-height: 14px;
    text-align: center;
    color: #FFF;
    font-weight: bold;
    font-size: 14px;
    cursor: pointer;
}

footer {
    color: #666;
    font-size: 14px;
    text-align: center;
}

footer a {
    color: #666;
    text-decoration: none;
    color: #999;
}

@media screen and (max-device-width: 620px) {
    section {
        width: 96%;
        padding: 0 2%;
    }
}

@media screen and (min-width: 620px) {
    section {
        width: 600px;
        padding: 0 10px;
    }
}
  • html and css
<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <title>ToDoList—Simplest to-do list</title>
    <link rel="stylesheet" href="css/index.css">
    <script src="js/jquery.min.js"></script>

</head>

<body>
    <header>
        <section>
            <label for="title">ToDoList</label>
            <input type="text" id="title" name="title" placeholder="add to ToDo" required="required" autocomplete="off" />
        </section>
    </header>
    <section>
        <h2>underway <span id="todocount"></span></h2>
        <ol id="todolist" class="demo-box">

        </ol>
        <h2>Already completed <span id="donecount"></span></h2>
        <ul id="donelist">

        </ul>


    </section>
    <footer>
        Copyright &copy; 2014 todolist.cn
    </footer>

    <script>
        $(function() {


            // Objects stored in localstroage
            var todolist = [

            ];

            // Load on page refresh
            flesh();

            // Today's task input box gets the focus, and enter enter to save the data
            $("#title").on("focus", function() {
                $(document).on("keypress", function(e) {
                    if (e.keyCode == 13) {
                        // alert(11);
                        // Create a task object
                        var todoObj = {};
                        todoObj.test = $("#title").val();
                        todoObj.done = false;
                        // Add task object to array
                        todolist.push(todoObj);

                        console.log(todoObj);
                        // Store to localstorage
                        localStorage.setItem("todolist", JSON.stringify(todolist));
                        // Refresh page
                        flesh();
                    }
                })
            })

            // Switch between running and completed tasks
            function mytog(done1, now) {
                var text = now.parent("li").text();
                var num = 0;
                console.log(1);
                /* 
                    Optimized traversal operation
                */
                $.each(todolist, function(index, ele) {

                        if (ele.test == text) {
                            num = index;
                            console.log(num);
                            return false;
                            // break;
                        }

                    })
                    // console.log(index);
                todolist[num].done = done1;
                // console.log(todolist);
                // now.prop("checked", true);
                localStorage.setItem("todolist", JSON.stringify(todolist));
                flesh();
            }


            // Delete task
            function del(now) {
                var text = now.parent("li").text();
                var num = 0;
                console.log(1);
                /* 
                    Optimized traversal operation
                */
                $.each(todolist, function(index, ele) {

                        if (ele.test == text) {
                            num = index;
                            console.log(num);
                            return false;
                            // break;
                        }

                    })
                    // console.log(index);
                    // Delete array elements
                todolist.splice(num, 1);
                // todolist[num].done = done1;
                // console.log(todolist);
                localStorage.setItem("todolist", JSON.stringify(todolist));
                flesh();
            }

            // Switch complete
            $("ol").on("click", "li input", function() {
                var now = $(this);
                mytog(true, now);
            })

            // Switch not completed
            $("ul ").on("click", "li input", function() {
                var now = $(this);
                mytog(false, now);
            })

            // Delete operation
            $("ul").on("click", "li a", function() {
                del($(this));
            })

            $("ol").on("click", "li a", function() {
                del($(this));
            })



            // Refresh screen
            function flesh() {
                if (localStorage.getItem("todolist")) {
                    todolist = JSON.parse(localStorage.getItem("todolist"));
                } else {
                    todolist = [];
                }

                var cntTrue = 0;
                var cntFalse = 0;
                $("ol").html("");
                $("ul").html("");

                /* 
                
                        In this part, there is a better way to add the index number of the corresponding object to the a tag in each created li tag
                        It can simplify the operation of traversing and finding index numbers above
                
                */
                $.each(todolist, function(index, ele) {

                    if (ele.done == false) {
                        // Create a new li tag
                        var li = $("<li><input type='checkbox'>" + ele.test + "<a href='#'></a></li>");
                        $("ol").append(li);
                        cntFalse++;
                        $("h2 span#todocount").html(cntFalse);
                    } else if (ele.done == true) {
                        // Create the completed li tag
                        var li = $("<li><input type='checkbox' checked>" + ele.test + "<a href='#'></a></li>");
                        $("ul").append(li);
                        cntTrue++;
                        $("h2 span#donecount").html(cntTrue);
                    }
                })

                if (cntTrue == 0) {
                    $("h2 span#donecount").html("");
                }

                if (cntFalse == 0) {
                    $("h2 span#todocount").html("");

                }
            }



        })
    </script>


</body>

</html>
  • design sketch

Attention

  • Pay attention to dynamic binding when binding events, because the li tag sometimes does not exist. You must use on to bind events
  • Events must be bound with ul (resident)
$("ol").on("click", "li input", function() {
                var now = $(this);
                mytog(true, now);
            })

Topics: Javascript JQuery