Day50 前端基础--jQuery 2

一,jQuery基础

  1.位置操作  

//位置操作方法
.offset() //获取匹配元素在当前窗口的相对偏移,或设置元素位置 .position() //获取匹配元素相对父元素的偏移 .scrollTop() //获取匹配元素相对滚动条顶部的编移 .scrollLeft() //获取匹配元素相对滚动条左侧的偏移 .offset()和.position()的差别: .offset()方法允许我们检索一个元素相对于文档(document)的当前位置 .position()是相对于父级元素的位移
$(".c2").offset()
{top: 0, left: 200}
$(".c2").position() //相对父元素的偏移
{top: 0, left: 100}
$(".c2").offset({top:100,left:200})  //设置元素位置
jQuery.fn.init [div.c2, prevObject: jQuery.fn.init(1)]
$(window).scrollTop()  //获取页面整体相对滚动条顶部的偏移
$(window).scrollTop(0)  //返回页面顶部

  2.尺寸大小

    内容(content)>内填充(padding)>边框(border)>外边距(margin)

.height(),.width()   //内容的宽度和高度
.innerHeight(),.innerWidth()  //内填充+内容的宽度和高度
.outerHeight(),.outerWidth()  //外填充+边框+内填充+内容的高度或宽度
.c1 {
    height: 100px;
     200px;
    background-color: red;
    padding: 10px;
    margin-left: 100px;
    border: 5px solid green;
}


$(".c1").height()
100
$(".c1").width()
200
$(".c1").innerHeight()  //内容的高度+内填充
120
$(".c1").innerWidth()   //内容的宽度+内填充
220
$(".c1").outerHeight()  //内容的高度+内填充+边框+外填充
130
$(".c1").outerWidth()   //内容的宽度+内填充+边框+外填充
230

  3.文本操作

    1.text()

text() //取得所有匹配元素的内容
text(val)  //设置所有匹配元素的内容

//text('<a href="www.123.com">123</a>'),text()方法不能识别a标签

    2.html()

html()  //取得第一个匹配元素的html内容
html(val)  //设置所有匹配元素的html内容

    3.val()

val()  //取得第一个匹配元素的当前值
val(val)  //设置所有匹配元素的值
val([val1, val2])  //设置多选的checkbox,多选select的值

$("[name=hobby]").val(['basketball','football']);
$("input[name='hobby']:checked").val(); //返回"basketball",获取用户输入时,如果用户输入的值为多个的时候,val()方法只能获取到一个值
<!--登录示例-->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .error {
            color: red;
        }
    </style>
</head>
<body>

<form action="">
    <p>
        <label>用户名
            <input type="text" name="username">
        </label>
        <span class="error"></span>
    </p>
    <p>
        <label>密码
            <input id="pwd" type="text" name="password">
        </label>
        <span class="error"></span>
    </p>
    <p>
        <button id="login" type="button">登陆</button>
    </p>
</form>
<script src="jquery.js"></script>
<script>
    // 1. 找到的登陆按钮,绑定点击事件
    // $("#login")[0].onclick = function () {
    //     var $usernameInput = $('[name="username"]');
    //     var $passwordInput = $('[name="password"]');
    //     // 2. 获取用户名和密码输入框的值
    //     var usernameVal = $usernameInput.val();
    //     var passwordVal = $passwordInput.val();
    //     // 3. 判断值是否为空
    //     if (!usernameVal.trim()) {
    //         // 4. 如果是空,在对应的span.error标签中显示提示信息
    //         // 4.1 提示信息是什么?
    //         $usernameInput.parent().next('.error').text('用户名不能为空!')
    //     }
    //     if (!passwordVal.trim()) {
    //         // 4. 如果是空,在对应的span.error标签中显示提示信息
    //         // 4.1 提示信息是什么?
    //          $passwordInput.parent().next('.error').text('密码不能为空!')
    //     }
    //
    // }

    $("#login")[0].onclick = function () {
        // 1. 找到所有需要判断的input输入框
        var $inputEles = $("label>input");
        // 2. for玄幻依次做判断
        for (var i = 0; i < $inputEles.length; i++) {
            var $tmp = $($inputEles[i]);  // $(DOM对象) --> jQuery对象
            if (!$tmp.val().trim()) {
                var prefix = $tmp.parent().text().trim();
                $tmp.parent().next().text(prefix + '不能为空');
            }
        }
    };
    
    // 给获取用户u输入的input框绑定事件
    var $inputEles = $("label>input");
    for (var i = 0; i < $inputEles.length; i++) {
        $inputEles[i].onfocus = function () {
            $(this).parent().next().text("");
        }
    }

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

  4.属性

    prop和attr的区别:

      attr全称attribute(属性)

      prop全称property(属性)

    虽然都是属性,但他们所指的属性并不相同,atr所指的属性是html标签属性,而prop所指的是DOM属性,可以认为attr是显式的,而prop是隐式的。

//例:
<input type="checkbox" id="i1" value="1">

$("#i1").attr("checked")  // undefined
$("#i1").prop("checked")  // false

attr获取一个标签内没有的东西会得到undefined,而prop获取的是这个DOM对象的属性,因此checked为false


//例:
<input type="checkbox" checked id="i1" value="1">

$("#i1").attr("checked")   // checked
$("#i1").prop("checked")  // true

attr的局限性,它的作用范围只限于HTML标签内的属性,而prop获取的时这个DOM对象的属性,选中返回true,没选中返回false


//例:
<input type="checkbox" checked id="i1" value="1" me="自定义属性">

$("#i1").attr("me")   // "自定义属性"
$("#i1").prop("me")  // undefined

prop不支持获取标签的自定义属性

    1.想要获取文本类的属性和自定义属性用attr(标签上写的属性attr) 

//用于ID等或自定义属性:
attr(attrName)// 返回第一个匹配元素的属性值
attr(attrName, attrValue)// 为所有匹配元素设置一个属性值
attr({k1: v1, k2:v2})// 为所有匹配元素设置多个属性值
removeAttr()// 从每一个匹配的元素中删除一个属性

    2.想要获取返回布尔值的属性用prop,比如checkbox、radio和option的是否被选中都用prop(DOM对象有的属性用prop)

//用于checkbox、radio和option
prop() // 获取属性
removeProp() // 移除属性

    注意:在1.x及2.x版本的jQuery中使用attr对checkbox进行赋值操作时会作出bug,在3.x版本的jQuery中则没有这个问题。为了兼容性,我们在处理checkbox和radio的时候尽量使用特定的prop(),不要使用attr("checked","checked")

<!--实例:全选、反选、取消-->

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

<button id="all">全选</button>
<button id="reverse">反选</button>
<button id="cancel">取消</button>
<table border="1">
   <thead>
    <tr>
        <th>#</th>
        <th>姓名</th>
        <th>爱好</th>
    </tr>
   </thead>
    <tbody>
    <tr>
        <td><input type="checkbox"></td>
        <td>金老板</td>
        <td>开车</td>
    </tr>
    <tr>
        <td><input type="checkbox"></td>
        <td>景女神</td>
        <td>茶道</td>
    </tr>
    <tr>
        <td><input type="checkbox"></td>
        <td>苑昊(苑局)</td>
        <td>不洗头、不翻车、不要脸</td>
    </tr>
    </tbody>
</table>

<script src="jquery.js"></script>
<script>
    // 点击全选按钮 选中所有的checkbox
    // DOM绑定事件方法
    // $("#all")[0].onclick = function(){}
    // jQuery绑定事件方法
    $("#all").click(function () {
        $(":checkbox").prop('checked', true);
    });
    // 取消
    $("#cancel").on("click", function () {
         $(":checkbox").prop('checked', false);
    });
    // 反选
    $("#reverse").click(function () {
        // 1. 找到所有选中的checkbox取消选中
        // $("input:checked").prop('checked', false);
        // // 2. 找到没有选中的checkbox选中
        // $("input:not(:checked)").prop('checked', true);

        // 1. for循环所有的checkbox,挨个判断原来选中就取消选中,原来没选中就选中
        var $checkbox = $(":checkbox");
        for (var i=0;i<$checkbox.length;i++){
            // 获取原来的选中与否的状态
            var status = $($checkbox[i]).prop('checked');
            $($checkbox[i]).prop('checked', !status);
        }
        // 2. 先用变量把原来的状态保存下来
    //     var $unchecked =  $("input:not(:checked)");
    //     var $checked = $("input:checked");
    //
    //     $unchecked.prop('checked', true);
    //     $checked.prop('checked', false);
    })

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

  5.文档操作

    1.内部追加(子级)

      1.往前追加:添加到指定元素内部的前面      

$(A).prepend(B)// 把B前置到A
$(A).prependTo(B)// 把A前置到B

      2.往后追加:添加到指定元素内部的后面

$(A).append(B)// 把B追加到A
$(A).appendTo(B)// 把A追加到B

    

    2.外部添加(同级)

      1.往前加:添加到指定元素外部的前面

$(A).before(B)// 把B放到A的前面
$(A).insertBefore(B)// 把A放到B的前面

      2.往后加:添加到指定元素外部的后面

$(A).after(B)// 把B放到A的后面
$(A).insertAfter(B)// 把A放到B的后面

    3.替换

$("A").replaceWith(B)  //将A替换为B
$("B").replaceAll($("A"))  //用B替换所有A

    4.移除和清空元素

remove()// 从DOM树上删除所有匹配的元素。
empty()// 删除匹配的元素集合中所有的子节点。

    

    5.克隆

clone()  //只克隆文档,
clone(true)  //文档和事件都克隆,克隆的目标,继承母版的事件

      

  

原文地址:https://www.cnblogs.com/lianyeah/p/9811725.html