jquery (2) 基础语法

144 阅读4分钟

1. 基本操作

概念:

  • 内容操作:
    • 元素.text():获取元素的纯文本内容,对元素集合操作则将全部结果进行拼接。
    • 元素.text("v"):设置元素的纯文本内容,对元素集合操作则将所有元素都依次设置。
    • 元素.html():获取元素的HTML内容,对元素集合操作则将全部结果进行拼接。
    • 元素.html("v"):设置元素的HTML内容,对元素集合操作则将所有元素都依次设置。
  • 属性操作:
    • 元素.attr("k"):获取元素的 k 属性,忽略大小写,若 k 不存在返回 undefined
    • 元素.attr("k", "v"):设置元素的 k 属性为 v
    • 元素.attr("k", (i, v) => {}):设置元素的 k 属性为匿名函数的返回值:
    • 元素.attr({}):利用JSON对的格式同时设置多条属性和值。
    • 元素.removeAttr("k"):移除元素中的 k 属性。
    • 元素.val():快速获取元素的 value 属性值,若不存在返回空字符串。
    • 元素.val("v"):快速设置元素的 value 属性值为 v
    • 元素.hasClass(a):判断元素的 class 属性的空格拆分值中是否包含 a
    • 元素.addClass(a):为元素添加 class 属性并添加值 a
    • 元素.removeClass(a):从元素的 class 属性中移除 class=a
    • 元素.toggleClass(a):切换元素的 class 默认值和 a,多样式切换用空格隔开。
  • 样式操作:
    • 元素.css("k"):获取元素的 k 样式。
    • 元素.css([k1, k2]):同时获取元素的 k1k2 样式,返回一个JSON。
    • 元素.css("k", "v"):设置元素的 k 样式为 v
    • 元素.css("k", (i, v) => {}):设置元素中的 k 样式为匿名函数的返回值:
    • 元素.css({}):利用JSON对的格式同时设置多条样式和值。
    • 元素.width():快速获取元素宽度,返回number类型。
    • 元素.height():快速获取元素高度,返回number类型。
    • 元素.width(v):快速设置元素宽度,支持使用number类型参数。
    • 元素.height(v):快速设置元素高度,支持使用number类型参数。
    • 元素.innerWidth():快速获取元素宽度 + 左右内边距。
    • 元素.outerWidth():快速获取元素宽度 + 左右内边距 + 左右边框。
    • 元素.outerWidth(true):快速获取元素宽度 + 左右内边距 + 左右边框 + 左右外边距。
    • 元素.innerHeight():快速获取元素高度 + 上下内边距。
    • 元素.outerHeight():快速获取元素高度 + 上下内边距 + 上下边框。
    • 元素.outerHeight(true):快速获取元素高度 + 上下内边距 + 上下边框 + 上下外边距。
  • 定位操作:
    • 元素.offset().left:获取元素相对于视口原点的左距离。
    • 元素.offset().top:获取元素相对于视口原点的上距离。
    • 元素.position().left:获取元素相对于最近的父元素(需定位)原点的左距离。
    • 元素.position().top: 获取元素相对于最近的定位父元素(需定位)原点的上距离。
    • $(window).scrollTop():获取当前窗口滚动条的垂直位置。
    • $(window).scrollTop(300):设置当前窗口滚动条的垂直位置,参数不能有单位。
    • $(window).scrollLeft():获取当前窗口滚动条的水平位置。
    • $(window).scrollLeft(300):设置当前窗口滚动条的水平位置,参数不能有单位。

内容操作

布局:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<section id="first-sec">hello</section>
<section>wor</section>
<section>ld</section>

<button id="text-btn">操作元素的TEXT内容</button>
<br/>
<button id="html-btn">操作元素的HTML内容</button>
<br/>

<script type="text/javascript" src="../../script/jquery-3.2.1.js"></script>
<script type="text/javascript">
    $(() => {
        let firstSec = $("#first-sec");
        let sections = $("section");

        $("#text-btn")[0].onclick = () => {
            console.log(firstSec.text());
            firstSec.text("??");
            console.log(firstSec.text());
            firstSec.text("<h1>??</h1>");
            console.log(firstSec.text());

            console.log(sections.text());
            sections.text("??");
            console.log(sections.text());
            sections.text("<h1>??</h1>");
            console.log(sections.text());

        };

        $("#html-btn")[0].onclick = () => {
            console.log(firstSec.html());
            firstSec.html("??");
            console.log(firstSec.html());
            firstSec.html("<h1>??</h1>");
            console.log(firstSec.html());

            console.log(sections.html());
            sections.html("??");
            console.log(sections.html());
            sections.html("<h1>??</h1>");
            console.log(sections.html());
        };
    });
</script>
</body>
</html>

属性操作

布局:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        .a {
            background: red;
        }

        .b {
            background: green;
        }
    </style>
</head>
<body>

<section id="field-sec"></section>
<label><input id="field-input"/></label>
<article id="field-art">article</article>
<footer id="field-footer" class="a">footer</footer>

<button id="attr-btn">操作元素的ID属性</button>
<br/>
<button id="val-btn">操作元素的value属性</button>
<br/>
<button id="class-btn">操作元素的class属性</button>
<br/>
<button id="toggle-class-btn">切换元素的class属性</button>
<br/>

<script type="text/javascript" src="../../script/jquery-3.2.1.js"></script>
<script type="text/javascript">
    $(() => {
        let fieldSec = $("#field-sec");
        let fieldInput = $("#field-input");
        let fieldArt = $("#field-art");
        let fieldFooter = $("#field-footer");

        $("#attr-btn")[0].onclick = () => {
            console.log(fieldSec.attr("id"));
            console.log(fieldSec.attr("ID"));

            fieldSec.attr("id", "attr-btn-1");
            console.log(fieldSec.attr("id"));

            fieldSec.attr("id", (i, v) => {
                console.log("i=", i);
                console.log("v=", v);
                return "attr-btn-2";
            });
            console.log(fieldSec.attr("id"));

            fieldSec.attr({
                "id": "attr-btn-3",
                "name": "name-3"
            });
            console.log(fieldSec.attr("id"));
            console.log(fieldSec.attr("name"));

            fieldSec.removeAttr("name");
            console.log(fieldSec.attr("id"));
            console.log(fieldSec.attr("name"));
        };

        $("#val-btn")[0].onclick = () => {
            console.log(fieldInput.val());
            fieldArt.val("hello");
            console.log(fieldInput.val());
        };

        $("#class-btn")[0].onclick = () => {
            console.log(fieldArt.hasClass("a"));

            fieldArt.addClass("a");
            fieldArt.addClass("b");
            console.log(fieldArt.hasClass("a"));
            console.log(fieldArt.hasClass("b"));

            fieldArt.removeClass("b");
            console.log(fieldArt.hasClass("a"));
            console.log(fieldArt.hasClass("b"));
        };

        $("#toggle-class-btn")[0].onclick = () => {
            fieldFooter.toggleClass("b");
        };
    });
</script>


</body>
</html>

样式操作

布局:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        #css-sec {
            width: 100px;
            height: 50px;
            background-color: red;
            margin: 30px;
            padding: 20px;
            border: 10px solid red;
        }
    </style>
</head>
<body>

<section id="css-sec"></section>

<button id="css-btn">操作元素的样式</button>
<br/>
<button id="size-btn">操作元素的尺寸</button>
<br/>

<script type="text/javascript" src="../../script/jquery-3.2.1.js"></script>
<script type="text/javascript">
    $(() => {
        let cssSec = $("#css-sec");

        $("#css-btn")[0].onclick = () => {
            console.log(cssSec.css("width"));

            console.log(cssSec.css(["width", "height"]));

            cssSec.css("width", "200px");
            console.log(cssSec.css("width"));

            cssSec.css("width", (i, v) => {
                console.log("i=", i);
                console.log("v=", v);
                return "300px";
            });
            console.log(cssSec.css("width"));

            cssSec.css({
                "width": "400px",
                "height": "400px",
                "backgroundColor": "green"
            });
            console.log(cssSec.css(["width", "height", "backgroundColor"]));
        };

        $("#size-btn")[0].onclick = () => {
            console.log("width:", cssSec.width());
            console.log("height:", cssSec.height());

            cssSec.width(200);
            cssSec.height("100px");
            console.log("width:", cssSec.width());
            console.log("height:", cssSec.height());

            console.log("innerWidth:", cssSec.innerWidth());
            console.log("outerWidth:", cssSec.outerWidth());
            console.log("outerWidth-true:", cssSec.outerWidth(true));
            console.log("innerHeight:", cssSec.innerHeight());
            console.log("outerHeight:", cssSec.outerHeight());
            console.log("outerHeight-true:", cssSec.outerHeight(true));
        };

    });
</script>
</body>
</html>

定位操作

布局:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        body {
            margin: 0;
            width: 3000px;
            height: 5000px;
        }

        #father {
            margin-top: 100px;
            margin-left: 50px;
            padding-top: 10px;
            padding-left: 20px;
            position: absolute;
        }
    </style>
</head>
<body>
<section id="father">
    <div id="son"></div>
</section>

<hr/>
<button id="offset-btn" type="button">子元素相对视口的距离</button>
<br/>
<button id="position-btn" type="button">子元素相对父元素的距离</button>
<br/>
<button id="scroll-btn" type="button">滚动条位置</button>
<br/>


<script type="text/javascript" src="../../script/jquery-3.2.1.js"></script>
<script type="text/javascript">
    $(() => {
        let son = $("#son");

        $("#offset-btn")[0].onclick = () => {
            console.log("left:", son.offset().left);
            console.log("top:", son.offset().top);
        };

        $("#position-btn")[0].onclick = () => {
            console.log("left:", son.position().left);
            console.log("top:", son.position().top);
        };

        $("#scroll-btn")[0].onclick = () => {
            $(window).scrollTop(100);
            $(window).scrollLeft(200);
            console.log("scrollTop:", $(window).scrollTop());
            console.log("scrollLeft:", $(window).scrollLeft());
        };
    });
</script>

</body>
</html>

2. 测试操作

概念: 测试操作返回值都是布尔类型:

  • $.type(对象):返回指定对象的类型。
  • $.isArray(对象):判断对象是否是一个array类型。
  • $.isFunction(对象):判断对象是否是一个function类型。
  • $.isEmptyObject(对象):判断对象是否是null。
  • $.contains(原生对象A, 原生对象B):判断原生对象A中是否包含原生对象B。
  • $.isNumeric(对象):判断对象是否为number类型。
  • $.isWindow(对象):判断对象是否是window对象。

布局:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<section id="test-sec"></section>

<script type="text/javascript" src="../../script/jquery-3.2.1.js"></script>
<script type="text/javascript">
    $(() => {
        let testSec = $("#test-sec");
        console.log($.type(testSec));
        console.log($.isArray([1, 2, 3]));
        console.log($.isFunction(() => {
        }));
        console.log($.isEmptyObject(null));
        console.log($.contains($("body")[0], testSec[0]));
        console.log($.isNumeric(123));
        console.log($.isWindow(window));
    });

</script>

</body>
</html>

3. 字符操作

概念:

  • $.trim(str):字符串两端去空格。
  • $.param(json):将json改为查询串格式。

布局:

4. 数组操作

概念: 通过选择器获取到的DOM元素集合可以通过 元素集合.toArray() 的方式转换为数组:

  • $.each(o, (i, v) => {}):通用遍历法,可用于遍历JQ对象集合,数组或者JSON:
    • param1:角标序号,或者JSON的key值。
    • param2:对应角标位置上的内容,或者JSON的value值。
    • 如果需要退出循环可使函数返回false即可。
  • o.each((i, v)=>{ }):元素遍历法,更适用于遍历JQ对象集合,数组或者JSON无法使用:
    • param1:角标序号。
    • param2:对应角标位置上的内容。
    • 如果需要退出循环可使函数返回false即可。
  • $.extend(接收者,赠与者列表):将所有赠与者的值依次继承到接收者身上,最终结果被返回,也同时直接作用在接收者身上:
    • 如果接收者是一个数组对象,则继承的原则是按角标替代。
    • 如果接收者是一个JSON对象,则继承的原则是重名覆盖,异名添加。
  • $.merge(arrA, arrB):将数组不去重合并然后返回,只能操作两个数组且不适用于JSON:
    • return:返回一个新数组,且合并结果也作用于原数组。
  • $.grep(arr, fn, invert):过滤数组元素:
    • param1:待过滤数组。
    • param2:过滤函数,每个元素依次调用该函数,若返回 true 则表示该元素被选中,但是留是删,还要取决于param3。
    • param3:默认为false,表示将过滤函数选中的所有元素保留,其余元素删除,true则相反。
    • return:返回一个新数组,且过滤结果不作用于原数组。
  • $.map(arr, fn):将数组中的元素按角标部署到另一个数组中:
    • param1:待部署数组。
    • param2:部署函数,每个元素依次调用该函数,并用返回值按角标覆盖原值,返回null表示删除。
    • return:返回一个新数组,且部署结果不作用于原数组。
  • $.unique(arr):将数组中的重复元素删除。
    • param1:待去重数组。
    • return:返回一个新数组,且去重结果也作用于原数组。
  • $.inArray(e, arr):在数组中查找元素第一次出现的位置:
    • param1:待查找元素。
    • param2:指定数组。
    • return:返回元素 e 在指定数组中的位置,返回-1表示不存在。

布局:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>111</div>
<div>222</div>
<div>333</div>
<div>444</div>

<button id="to-array-btn" type="button">toArray()</button>
<br/>
<button id="comm-each-btn" type="button">$.each()</button>
<br/>
<button id="element-each-btn" type="button">o.each()</button>
<br/>
<button id="extends-btn" type="button">$.extends()</button>
<br/>
<button id="merge-btn" type="button">$.merge()</button>
<br/>
<button id="grep-btn" type="button">$.grep()</button>
<br/>
<button id="map-btn" type="button">$.map()</button>
<br/>
<button id="unique-btn" type="button">$.unique()</button>
<br/>
<button id="in-array-btn" type="button">$.inArray()</button>
<br/>

<script type="text/javascript" src="../../script/jquery-3.2.1.js"></script>
<script type="text/javascript">
    $(() => {
        let divs = $("div");

        $("#to-array-btn")[0].onclick = () => {
            console.log($.type(divs));
            console.log($.type(divs.toArray()));
        };

        $("#comm-each-btn")[0].onclick = () => {
            $.each(divs, (i, v) => {
                if (i === 3) {
                    return false;
                }
                console.log(i, v);
            });

            let array = [5, 6, 7];
            $.each(array, (i, v) => {
                console.log(i, v);
            });

            let json = {"name": "jack", "age": 18};
            $.each(json, (k, v) => {
                console.log(k, v);
            });
        };

        $("#element-each-btn")[0].onclick = () => {
            divs.each((i, v) => {
                if (i === 3) {
                    return false;
                }
                console.log(i, v);
            });
        };

        $("#extends-btn")[0].onclick = () => {

            let arr = [1, 2, 3];
            let arr1 = [4];
            let arr2 = [3, true];
            let arrResult = $.extend(arr, arr1, arr2);
            console.log("arr:", arr);
            console.log("arr1:", arr1);
            console.log("arr2:", arr2);
            console.log("arrResult:", arrResult);

            let json = {a: 1, b: 2};
            let json1 = {c: 3};
            let json2 = {a: 4, b: 5};
            let jsonResult = $.extend(json, json1, json2);
            console.log("json:", json);
            console.log("json1:", json1);
            console.log("json2:", json2);
            console.log("jsonResult:", jsonResult);
        };

        $("#merge-btn")[0].onclick = () => {
            let arr = [1, 3, 5];
            let arr1 = [3, 5, 7];
            let arrResult = $.merge(arr, arr1);
            console.log("arr:", arr);
            console.log("arr1:", arr1);
            console.log("arrResult:", arrResult);
        };

        $("#grep-btn")[0].onclick = () => {
            let arr = [1, 2, 3, 4, 5];
            let arrResultA = $.grep(arr, (v, i) => v > 2, true);
            let arrResultB = $.grep(arr, (v, i) => v > 2, false);
            console.log(arr);
            console.log(arrResultA);
            console.log(arrResultB);
        };

        $("#map-btn")[0].onclick = () => {
            let arr = [1, 2, 3];
            let arrResult = $.map(arr, (v, i) => v * 2);
            console.log(arr);
            console.log(arrResult);
        };

        $("#unique-btn")[0].onclick = () => {
            let arr = [1, 1, 1, 3, 3, 3, 4];
            let arrResult = $.unique(arr);
            console.log(arr);
            console.log(arrResult);
        };

        $("#in-array-btn")[0].onclick = () => {
            let arr = [1, 1, 1, 3, 3, 3, 4];
            let result1 = $.inArray(3, arr);
            let result2 = $.inArray(5, arr);
            console.log(result1);
            console.log(result2);
        };
    });
</script>
</body>
</html>