Basic operations of Jquery

Keywords: Front-end html5 JQuery

1, Method of use

   jQuery does not need to be installed. To use it, you only need to import a js file, which can be placed on an external site or on your own server. However, in the actual development process, it is more convenient to use the local server.
  major development companies provide CDN downloaded by jquery. This courseware is based on jquery 2.1.4 of Baidu CDN. You can use the following path to introduce jquery.

<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>

  in actual development, the third-party server may be inaccessible to jquery due to third-party factors such as network and self startup, so it is recommended to download it locally.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>quote jQuery library</title>
<script src="js/jquery.js"></script>
</head>
<body>
<div id="div"></div>
<script>
    // document.getElementById("div").innerHTML="hello world!"
    $("#div").html("hello world!!");
</script>
</body>
</html>

    after the code that references the style sheet file, the code that contains the JavaScript file. Here, it should be noted that the < script > tag that references the jQuery library file must be placed before the < script > tag that references the custom script file. Otherwise, the jQuery framework will not be referenced in the code written in the custom script file.

2, Selector

   jQuery allows fast and accurate selection of DOM elements by tag name, attribute name or content without worrying about browser compatibility. Compared with traditional JavaScript to get page elements and write transactions, jQuery selector has obvious advantages.

   basic selector: the basic selector is the most frequently used selector in jQuery. It is composed of element id, class, element name and multiple selectors. Through the basic selector, you can find most page elements. The specific instructions are as follows.

#id matches an element to a single element according to the provided id attribute value
Element    Match all elements according to the provided element name             Element collection
.class     Match all elements according to the class name provided             Element collection
*          Match all elements                               Element collection
s1,sn      After merging the elements to which each selector matches-Start and return    Element collection

Case:

<body>
<div id="div"></div>
<span></span>
<span></span>
<span></span>
<div class="class_div"></div>
<div class="class_div"></div>
<div class="class_div"></div>
<div class="class_div"></div>
<ul class="my_div">
    <li></li>
    <li></li>
    <li></li>
    <li></li>
</ul>
<script src="js/jquery.js"></script>
<script>
    $("#div").html("hello world!")
    $("span").html("123465")
    $(".class_div").html("<h1>123465</h1>")
    $(".my_div li").text("<h1>123</h1>")
    $(".my_div li,span").text("<h1>1</h1>")
</script>
</body>

3, Add node

  to dynamically create a div element in the page and set its content and properties, the specific code is as follows:

var div = "<div class='new_class'>Create new div block</div>";
$("body").append(div);

  as can be seen from the above, the dynamic creation of elements in the page requires the insertion or addition of nodes. In jQuery, there are many methods to realize this function. The append() method used in the above example is only one of them. According to the order of inserting elements, the insertion node can be divided into internal insertion and external insertion.
① Internal insert node

② External insert node

Case:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>java Learning platform</title>
    <script src="js/jquery.min.js"></script>
</head>
<body>
<span id="span3">3</span>
<div id="append">
    <span>1</span>
</div>
<div id="prepend">
    <span>1</span>
</div>
<script>
    $("#append").append("<span>2</span>");
    $("#append").append($("#span3"));
    $("#prepend").prepend("<span>2</span>");
    $("#append").after("<span>4</span>");
    $("#append").before("<span>5</span>");
</script>
</body>
</html>

4, Delete node

    when DOM operates a page, it is often used to delete redundant or specified page elements. jQuery provides two methods to delete elements, namely remove() and empty(). Strictly speaking, the empty () method is not a real deletion. Using this method, you can only empty all nodes or all descendant elements contained in nodes, not delete nodes and elements. The syntax structure of the remove () method is as follows:

remove([expr])

   where the parameter expr is optional. If the parameter is accepted, the parameter is the jQuery expression for filtering elements, and the specified elements are obtained through the expression to delete.

The syntax structure of   empty() method is as follows:

empty()

Its function is to empty the selected page element and all its descendants.

Case:

<body>
<ul>
    <li title="1">This is the first news</li>
    <li title="2">This is the second news</li>
    <li title="3">This is the third news</li>
    <li title="4">This is the fourth news</li>
</ul>
<input type="button" value="Delete operation" id="btn1"/>
<input type="button" value="Emptying operation" id="btn2"/>
<script>
    //Click event
    $("#btn1").click(function () {
        $("ul li").remove("li[title=1]");
        $("ul li:eq(2)").remove();
    })
    $("#btn2").click(function () {
        $("ul").empty();
    })
</script>
</body>

5, Replace traversal node

    in jQuery, if you want to replace the node in the element, you can use the replaceWith() method. The syntax structure of the replaceWith() method is as follows:

replaceWith(content)

  the function of this method is to replace all selected elements with executed HTML or DOM elements, where the parameter content is the content replaced by the selected element.

Case:

<body>
<div>
    <p>full name:<span id="span1">Zhang San</span></p>
    <p>Class:<span id="span2">Class 1 of planning section</span></p>
    <input type="button" value="Click Replace" id="btn"/>
</div>
<span id="span3">test</span>
<script>
    //Click event
    $("#btn").click(function () {
        $("#Span1 "). Replacewith (" < span > Li Si < / span > ");
        $("#span2").replaceWith($("#span3"));
    })
</script>
</body>

Traversal node

   in DOM element operation, it is sometimes necessary to operate all elements uniformly marked. In JavaScript, you need to obtain the total length of the element first, and then use the for statement to process it circularly. In jQuery, you can easily use each() method to realize the element history. Its syntax structure is as follows:

each(callback)

   the parameter callback is a function function that can also accept a formal parameter index and the DOM element currently traversed (not a jQuery object). This formal parameter is the sequence number of the traversing element (starting from 0); if you need to access the attributes in the element, you can use the formal parameter index and the this keyword to set or obtain the element attributes.

Case:

<ul>
    <li>This is the first news</li>
    <li>This is the second news</li>
    <li>This is the third news</li>
    <li>This is the fourth news</li>
</ul>
<input type="button" value="Add sequence number to news" id="btn"/>
<script>
    //Click event
    $("#btn").click(function () {
        $("ul li").each(function (i, j) {
            console.info(i, j)
            console.info(j.innerHTML)
            console.info($(j).html())
            //Add sequence number to news
            let content = $(this).text();
            console.info(content)
            $(this).html(i + 1 + "," + content);
        })
    })
</script>

6, Attribute style action

    in jQuery, you can get, set, and delete the attributes of an element. You can get and set the attributes of an element through the attr() method, and you can delete the attributes of an element through the removeAttr() method.

  (1) get element attributes

   the attribute of an element can be obtained through the attr() method, and its syntax structure is as follows:

attr(name)

   where the parameter name represents the name of the attribute, and the attribute value of the element is obtained by taking the element attribute name as the parameter.

   (2) set the attributes of the element

    in the page, the attr() method can be used not only to obtain the attribute value of the element, but also to set the attribute of the element. The syntax format for setting the attribute of the element is as follows:

attr(key,value)

   where the parameter key represents the name of the attribute and the value represents the value of the attribute. If you want to set multiple attributes, you can also use the attr() method. Its syntax structure is as follows:

attr({key0:value0,key1:value1})

  (3) delete element attributes
    after setting the attribute of an element through the attr() method in jQuery, you can delete the attribute of the element by using the removeAttr() method. Its syntax structure is as follows:

removeAttr(name)

  where parameter name is the name of the element attribute.

<body>
<ul title="News list">
    <li>This is the first news</li>
    <li>This is the second news</li>
    <li>This is the third news</li>
    <li>This is the fourth news</li>
</ul>
<input type="button" value="Attribute operation" id="btn"/>
<script>
    $("#btn").click(function () {
        console.info($("ul").attr("title"));
        $("ul").attr("title", "My news list");
        $("ul").attr({"title": "My news list", class: "list"});
        $("ul").removeAttr("title");
    })
</script>
</body>

Style operation
  in the page, the style operation of elements includes four parts: directly setting styles, adding CSS categories, category switching and deleting categories.

(1) Style elements directly

    in jQuery, you can directly set the style value for a specified element through the css() method. Its syntax structure is as follows:

css(name,value)

   where name is the style name and value is the style value. For example, you can use the following code to make the font of p element thicker. Its syntax structure is as follows:

$("p").css("font-weight","bold");

(2) Add CSS category

   the name of the element class can be added through the addClass() method. Its syntax structure is as follows:

addClass(class)

   where, the parameter class is the name of the category, or you can add the names of multiple categories. You only need to separate them with spaces. Its syntax structure is as follows:

addClass(class0 class1..)

(3) Category switching
    you can switch different element classes through the toggleClass() method. Its syntax structure is as follows: toggleClass(class), where the parameter class is the class name. Its function is to delete the class name when the element contains a CSS class with the name class, otherwise add a CSS class with the name.

$(".div_frame").click(functionO{
    $(this).toggleClass("divred");
})

(4) Delete category
   corresponding to the addClass() method of adding CSS classes, the removeClass() method is used to delete classes. Its syntax structure is as follows:

removeClass([class])

   where the parameter class is the category name, which is optional. When the name is selected, the category with the name class will be deleted, and multiple categories will be separated by spaces. If you do not select the name, all categories in the element are deleted.

Case:

<body>
<ul title="News list">
    <li>This is the first news</li>
    <li>This is the second news</li>
    <li>This is the third news</li>
    <li class="red add">This is the fourth news</li>
</ul>
<input type="button" value="Style operation" id="btn"/>
<script>
    $("#btn").click(function () {
        $("li:eq(0)").css("font-weight", "bold");
        $("li:eq(1)").addClass("red")
        $("li:eq(2)").toggleClass("red")
        $("li:eq(3)").removeClass("red")
        $("li:eq(3)").removeAttr("class")
    })
</script>
</body>

practice:

1. Complete the following coding according to the design drawing

Reference code:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Chapter exercise</title>
    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js">
    </script>
    <style>
        * {
            margin: 0;
            padding: 0
        }

        .loadTxt {
            height: 50px;
            line-height: 50px;
            width: 531px;
            text-align: center;
            font-size: 30px;
            color: #29B6FF;
            font-family: Arial;
            margin: 0 auto;
        }

        .loadBox {
            height: 15px;
            background: #F5FAFD url(img/test2.jpg) no-repeat left center;
            width: 471px;
            position: relative;
            padding: 0 30px;
            margin: 0 auto;
        }

        .loadBox img {
            position: absolute;
            left: 50px;
            top: 0;
        }
    </style>
</head>
<body>

<div class="loadTxt">Loading<span>.</span><span>.</span><span>.</span></div>
<div class="loadBox">
    <img src="img/test1.jpg"/>
</div>

<script>
    var delVal = 50;
    function autoMove() {
        delVal++;
        if (delVal > 400) {
            delVal = 50;
        }
        $(".loadBox img").css("left", delVal);
    }

    setInterval(autoMove, 8);

    function autoTsq() {
        $(".loadTxt span").css("color", "#F5FAFD");
        setTimeout(function () {
            $(".loadTxt span").eq(0).css("color", "#29B6FF")
        }, 0);
        setTimeout(function () {
            $(".loadTxt span").eq(1).css("color", "#29B6FF")
        }, 500);
        setTimeout(function () {
            $(".loadTxt span").eq(2).css("color", "#29B6FF")
        }, 1000);
    }
    setInterval(autoTsq, 1500);
</script>
</body>
</html>

7, Content operation

    in jQuery, the methods to manipulate element content include html() and text(). The former is similar to innerHTML attribute in JavaScript, that is, to obtain and set the HTML content of the element; The latter is similar to the innerText attribute in JavaScript, that is, to get or set the text content of the element.

   the grammatical format and functional differences between the two are as follows.

html()            To get an element HTML content            nothing
html(value)       Used to set the name of the element HTML content            Parameter is the of the element HTML content
text()            Gets the text content of the element            nothing
text(value)       Used to set the text content of the element            The parameter is the text content of the element

    in jQuery, if you want to obtain the values of input and select elements, you can use the val() method. Its syntax structure is as follows:

val(value)

   if there is no parameter value, the value of the element is obtained; otherwise, the value of the parameter value is assigned to the element. This method is often used to obtain and set the value of the element object in the form. In addition, multiple option values of the select element can be obtained through the val() method. Its syntax structure is as follows:

val().join(",")

Case:

<body>
<div class="divframe">
    <select multiple="multiple">
        <option value="1">Item 1</option>
        <option value="2">Item 2</option>
        <option value="3">Item 3</option>
        <option value="4">Item 4</option>
        <option value="5">Item 5</option>
        <option value="6">Item 6</option>
    </select>
    <p id="p1"></p>
</div>
<div>
    <input type="text"/>
    <p id="p2"></p>
</div>
<script>
    //Event triggered when the value of the list box changes
    $("select").change(function () {
        //Gets the values of all the options selected in the list box
        var strSelect = $("select").val().join(",");
        //Displays the selected value
        $("#p1").html(strSelect);
    });
    //Event when the value of the text box changes (it is necessary to lose focus before verifying that the text content changes)
    $("input").change(function () {
        //Gets the value of the text box
        var strText = $("input").val();
        //Displays the selected value
        $("#p2").html(strText);
    });
    //Textbox focus event
    $("input").focus(function () {
        //Clear the value of the text box
        $("input").val("");
    });
</script>
</body>

   in the val(value) method, if there are parameters, the parameters can also be in the form of array, that is, val(array), which is used to set the element to be selected.

Exercise: Accordion menu: complete the exercise according to the following design drawing, click the corresponding parent menu to expand the internal sub menu. Click again to collapse the submenu.

Reference code:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>accordion</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        body {
            color: #09fbd2;
            text-align: center;
        }

        .menu {
            text-align: left;
            width: 400px;
            margin: 20px auto;
        }

        .menu .list {
            border-bottom: 1px solid #324252;
            list-style: none;
            background: #3e5165;
        }

        .menu .list a {
            text-decoration: none;
            color: #fff;
            padding: 17px 0px 17px 45px;
            display: block;
            height: 100%;
        }

        .menu .list > a {
            padding-left: 10px;
        }

        .menu .list > a:before {
            content: "▶";
            margin-right: 10px;
            color: white;
        }

        .menu .list.active > a:before {
            content: "▼";
        }

        .menu .list > a:after {
            content: "△";
            float: right;
            margin-right: 20px;
            color: white;
        }

        .menu .list.active > a:after {
            content: "▽";
        }

        .menu .list a:hover {
            background-color: #576676;
            color: #09fbd2;
        }

        .menu .items li {
            background-color: #324252;
            padding: 0px;
            border-bottom: 1px solid #3e5165;
            list-style: none;
        }

    </style>
    <script src="js/jquery.min.js"></script>
</head>
<body>
<h1>Accordion Menus (Accordion Menu)</h1>
<ul class="menu">
    <li class="list"><a href="#"> system management</a>
        <ul class="items">
            <li><a href="#"> User Management</a></li>
            <li><a href="#"> role management</a></li>
            <li><a href="#"> resource management</a></li>
        </ul>
    </li>

    <li class="list"><a href="#"> Product Configuration</a>
        <ul class="items">
            <li><a href="#"> commodity classification</a></li>
            <li><a href="#"> Product specifications</a></li>
            <li><a href="#"> commodity prices</a></li>
        </ul>
    </li>
    <li class="list"><a href="#"> business management</a>
        <ul class="items">
            <li><a href="#"> order business</a></li>
            <li><a href="#"> group business</a></li>
            <li><a href="#"> marketing business</a></li>
        </ul>
    </li>
</ul>

<script>
    $(".items").css("display", "none");

    function accordion() {
        if ($(this).find(".items").css("display") == "block") {
            $(this).find(">a").css({
                "color": "#fff",
                "font-weight": "normal",
            })
            $(this).removeClass("active")
            $(this).find(".items").css("display", "none")
        } else {
            $(this).find(">a").css({
                "color": "#09fbd2",
                "font-weight": "bold",
            })
            $(this).addClass("active")
            $(this).find(".items").css({"display": "block"});
        }
    }
    $('.list').bind('click', accordion);
</script>
</body>
</html>

2. Star rating: use jquery to complete the following star rating module.

Reference code:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Star rating</title>
    <style>
        * {
            margin: 0;
            padding: 0
        }

        .stars {
            margin: 10px;
            padding: 10px;
            border: 1px saddlebrown solid;
        }

        .stars span {
            float: left;
            height: 30px;
            line-height: 30px;
        }

        .stars i {
            width: 30px;
            height: 30px;
            line-height: 30px;
            float: left;
            margin-right: 30px;
            background: #ccc;
            color: #fff;
            text-align: center;
            cursor: default;
            font-style: normal;
        }

        .stars .on {
            color: #a71417;
        }

    </style>
    <script src="js/jquery.min.js"></script>
</head>
<body>
<div class="stars">
    <span>Commodity evaluation:</span>
    <i>★</i>
    <i>★</i>
    <i>★</i>
    <i>★</i>
    <i>★</i>
    <input type="text"/>
</div>
<div class="stars">
    <span>Merchant evaluation:</span>
    <i>★</i>
    <i>★</i>
    <i>★</i>
    <i>★</i>
    <i>★</i>
    <input type="text"/>
</div>
<div class="stars">
    <span>Logistics evaluation:</span>
    <i>★</i>
    <i>★</i>
    <i>★</i>
    <i>★</i>
    <i>★</i>
    <input type="text"/>
</div>

<script>

    $('.stars i').click(function () {
        let num = $(this).index();
        $(this).parent().children('i').removeClass('on');
        $(this).addClass('on').prevAll('i').addClass('on');
        $(this).siblings('input').val(num);
    });

    $('.stars i').mouseover(function () {
        $(this).parent().children('i').removeClass('on');
        $(this).addClass('on').prevAll('i').addClass('on');
    });

    $('.stars i').mouseout(function () {
        $(this).parent().children('i').removeClass('on');
        let score = $(this).siblings('input').val();
        for (let i = 0; i < score; i++) {
            $(this).parent().find('i').eq(i).addClass('on');
        }
    });

</script>
</body>
</html>

Posted by Lodius2000 on Fri, 19 Nov 2021 21:17:29 -0800