jQuery之事件

事件

常用事件

click(function(){...})
hover(function(){...})
blur(function(){...})
focus(function(){...})
change(function(){...})
keyup(function(){...})

 

hover 事件实例

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>hover事件示例</title>

    <style>

        body {

            margin: 0;

        }

 

        .nav {

            height: 40px;

            background-color: #3d3d3d;

            width: 100%;

        }

 

        ul {

            list-style-type: none;

            padding: 0;

            margin: 0;

        }

 

        a {

            text-decoration: none;

        }

 

        .nav a {

            color: #999;

        }

 

        .nav a:hover {

            color: white;

        }

 

        .nav li {

            float: left;

            height: 40px;

            line-height: 40px;

            margin-right: 15px;

            padding: 0 10px;

        }

 

        .nav li:hover {

            background-color: black;

        }

 

        .father {

            position: relative;

        }

 

        .son {

            height: 100px;

            width: 200px;

            background-color: blue;

            color: white;

            position: absolute;

            left: 0;

            top: 40px;

            margin: 0;

            display: none;

        }

        .show {

            display: block;

        }

    </style>

</head>

<body>

<div class="nav">

    <ul>

        <li><a href="">登录</a></li>

        <li><a href="">注册</a></li>

        <li class="father"><a href="">购物车</a>

            <p class="son">空空如也~</p>

        </li>

    </ul>

</div>

<script src="jquery-3.3.1.min.js"></script>

<script>

    // 鼠标移到 .father 上时 让 .son 添加一个 .show

    $(".father").hover(

            function () {

                $(this).find(".son").addClass("show");

            },

            function () {

                $(this).find(".son").removeClass("show");

            }

    )

</script>

</body>

</html>
View Code

keydown和keyup事件组合示例:

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>批量操作</title>

</head>

<body>

<table border="1">

  <thead>

  <tr>

    <th>#</th>

    <th>姓名</th>

    <th>操作</th>

  </tr>

  </thead>

  <tbody>

  <tr>

    <td><input type="checkbox"></td>

    <td>Egon</td>

    <td>

      <select>

        <option value="1">上线</option>

        <option value="2">下线</option>

        <option value="3">停职</option>

      </select>

    </td>

  </tr>

  <tr>

    <td><input type="checkbox"></td>

    <td>Alex</td>

    <td>

      <select>

        <option value="1">上线</option>

        <option value="2">下线</option>

        <option value="3">停职</option>

      </select>

    </td>

  </tr>

  <tr>

    <td><input type="checkbox"></td>

    <td>Yuan</td>

    <td>

      <select>

        <option value="1">上线</option>

        <option value="2">下线</option>

        <option value="3">停职</option>

      </select>

    </td>

  </tr>

  <tr>

    <td><input type="checkbox"></td>

    <td>EvaJ</td>

    <td>

      <select>

        <option value="1">上线</option>

        <option value="2">下线</option>

        <option value="3">停职</option>

      </select>

    </td>

  </tr>

  <tr>

    <td><input type="checkbox"></td>

    <td>Gold</td>

    <td>

      <select>

        <option value="1">上线</option>

        <option value="2">下线</option>

        <option value="3">停职</option>

      </select>

    </td>

  </tr>

  </tbody>

</table>

 

<input type="button" id="b1" value="全选">

<input type="button" id="b2" value="取消">

<input type="button" id="b3" value="反选">

 

<script src="jquery-3.3.1.min.js"></script>

 

 

<script>

 

    let flag = false;

    // 如何获取用户按下那个按键

    $(window).on("keydown", function (e) {

        console.log(e.keyCode);

        if (e.keyCode === 16){

            flag = true;

        }

    });

 

    // 绑定一个按键抬起的事件

    $(window).on("keyup", function (e) {

        console.log(e.keyCode);

        if (e.keyCode === 16){

            flag = false;

        }

    });

 

    // 找到 select标签 绑定 change事件

    $("select").on("change", function () {

        // 拿到当前select标签的值

        let v = $(this).val();

        // 判断一下当前行是否被选中

        let isCheck = $(this).parent().parent().find("input:checkbox").prop("checked");

        // 如果是批量编辑模式,就要找到所有被选中的行,然后将其select置为和我一样的值

        if (flag && isCheck){

            // 找到所有被选中的行

//            let $allChecked = $("input:checked");

//            for (let i=0;i<$allChecked.length;i++){

//                $($allChecked[i]).parent().parent().find("select").val(v);

//            }

 

            // 使用each循环

            $("input:checked").each(function () {

              $(this).parent().parent().find("select").val(v);

            })

        }

        // 如果不是批量编辑模式,什么都不干

    });

 

</script>

</body>

</html>

 
View Code

实时监听input输入值变化示例:

<!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">

  <title>实时监听input输入值变化</title>

</head>

<body>

<input type="text" id="i1">

 

<script src="jquery-3.2.1.min.js"></script>

<script>

  /*

  * oninput是HTML5的标准事件

  * 能够检测textarea,input:text,input:password和input:search这几个元素的内容变化,

  * 在内容修改后立即被触发,不像onchange事件需要失去焦点才触发

  * oninput事件在IE9以下版本不支持,需要使用IE特有的onpropertychange事件替代

  * 使用jQuery库的话直接使用on同时绑定这两个事件即可。

  * */

  $("#i1").on("input propertychange", function () {

    alert($(this).val());

  })

</script>

</body>

</html>

 

input值变化事件
View Code

focus和blur事件

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>focus和blur事件</title>

</head>

<body>

 

<input id="i1" type="text">

 

<script src="jquery-3.3.1.min.js"></script>

<script>

    // 当input框获取焦点时触发

    $("#i1").on("focus", function () {

        console.log(123);

    });

    // 当input框失去焦点时触发

    $("#i1").on("blur", function () {

        console.log($(this).val());

    });

    // 当input框的值发生变化时触发

    $("#i1").on("input", function () {

        console.log($(this).val());

    })

</script>

</body>

</html>
View Code

事件绑定

  1. .on( events [, selector ],function(){})
  • events: 事件
  • selector: 选择器(可选的)
  • function: 事件处理函数

移除事件

  1. .off( events [, selector ][,function(){}])

off() 方法移除用 .on()绑定的事件处理程序。

  • events: 事件
  • selector: 选择器(可选的)
  • function: 事件处理函数

阻止后续事件执行

  • return false; // 常见阻止表单提交等

注意:

像click、keydown等DOM中定义的事件,我们都可以使用`.on()`方法来绑定事件,但是`hover`这种jQuery中定义的事件就不能用`.on()`方法来绑定了。

想使用事件委托的方式绑定hover事件处理函数,可以参照如下代码分两步绑定事件:

 

$('ul').on('mouseenter', 'li', function() {//绑定鼠标进入事件
    $(this).addClass('hover');
});
$('ul').on('mouseleave', 'li', function() {//绑定鼠标划出事件
    $(this).removeClass('hover');
});

 

页面载入

当DOM载入就绪可以查询及操纵时绑定一个要执行的函数。这是事件模块中最重要的一个函数,因为它可以极大地提高web应用程序的响应速度。

两种写法:

$(document).ready(function(){
// 在这里写你的JS代码...
})

简写:

$(function(){
// 你在这里写你的代码
})

文档加载完绑定事件,并且阻止默认事件发生:

事件委托

事件委托是通过事件冒泡的原理,利用父标签去捕获子标签的事件。

示例:

表格中每一行的编辑和删除按钮都能触发相应的事件。

$("table").on("click", ".delete", function () {
  // 删除按钮绑定的事件
})

动画效果

// 基本
show([s,[e],[fn]])
hide([s,[e],[fn]])
toggle([s],[e],[fn])
// 滑动
slideDown([s],[e],[fn])
slideUp([s,[e],[fn]])
slideToggle([s],[e],[fn])
// 淡入淡出
fadeIn([s],[e],[fn])
fadeOut([s],[e],[fn])
fadeTo([[s],o,[e],[fn]])
fadeToggle([s,[e],[fn]])
// 自定义(了解即可)
animate(p,[s],[e],[fn])

 
View Code

点赞特效简单示例

<!DOCTYPE html>

<html lang="zh-CN">

<head>

  <meta charset="UTF-8">

  <meta http-equiv="x-ua-compatible" content="IE=edge">

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>点赞动画示例</title>

  <style>

    div {

      position: relative;

      display: inline-block;

    }

    div>i {

      display: inline-block;

      color: red;

      position: absolute;

      right: -16px;

      top: -5px;

      opacity: 1;

    }

  </style>

</head>

<body>

 

<div id="d1">点赞</div>

<script src="jquery-3.2.1.min.js"></script>

<script>

  $("#d1").on("click", function () {

    var newI = document.createElement("i");

    newI.innerText = "+1";

    $(this).append(newI);

    $(this).children("i").animate({

      opacity: 0

    }, 1000)

  })

</script>

</body>

</html>

 

点赞特效简单示例

 
View Code

二,补充

each

描述:一个通用的迭代函数,它可以用来无缝迭代对象和数组。数组和类似数组的对象通过一个长度属性(如一个函数的参数对象)来迭代数字索引,从0到length - 1。其他对象通过其属性名进行迭代。

li =[10,20,30,40]
$.each(li,function(i, v){
  console.log(i, v);//index是索引,ele是每次循环的具体元素。
})

输出:

010
120
230
340

.each(function(index, Element))

描述:遍历一个jQuery对象,为每个匹配元素执行一个函数。

.each() 方法用来迭代jQuery对象中的每一个DOM元素。每次回调函数执行时,会传递当前循环次数作为参数(从0开始计数)。由于回调函数是在当前DOM元素为上下文的语境中触发的,所以关键字 this 总是指向这个元素。

// 为每一个li标签添加foo
$("li").each(function(){
  $(this).addClass("c1");
});

注意: jQuery的方法返回一个jQuery对象,遍历jQuery集合中的元素 - 被称为隐式迭代的过程。当这种情况发生时,它通常不需要显式地循环的 .each()方法:

也就是说,上面的例子没有必要使用each()方法,直接像下面这样写就可以了:

$("li").addClass("c1");  // 对所有标签做统一操作

注意:

在遍历过程中可以使用 return false提前结束each循环。

终止each循环

return false;

 

.data()

在匹配的元素集合中的所有元素上存储任意相关数据或返回匹配的元素集合中的第一个元素的给定名称的数据存储的值。

.data(key, value):

描述:在匹配的元素上存储任意相关数据。

$("div").data("k",100);//给所有div标签都保存一个名为k,值为100

.data(key):

描述: 返回匹配的元素集合中的第一个元素的给定名称的数据存储的值—通过 .data(name, value)或 HTML5 data-*属性设置。

$("div").data("k");//返回第一个div标签中保存的"k"的值

.removeData(key):

描述:移除存放在元素上的数据,不加key参数表示移除所有保存的数据。

$("div").removeData("k");  //移除元素上存放k对应的数据

示例:

模态框编辑的数据回填表格

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>今日作业</title>
    <style>
        .cover {
            position: fixed;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
            background-color: rgba(0, 0, 0, 0.4);
            z-index: 9;
        }

        .modal {
            position: absolute;
            left: 50%;
            top: 50%;
            height: 300px;
            width: 400px;
            background-color: white;
            z-index: 100;
            margin-top: -150px;
            margin-left: -200px;
        }

        .hide {
            display: none;
        }
    </style>
</head>
<body>

<button id="add">新增</button>

<table border="1">
    <thead>
    <tr>
        <th>#</th>
        <th>姓名</th>
        <th>爱好</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td>1</td>
        <td>Egon</td>
        <td>喊麦</td>
        <td>
            <input type="button" value="编辑" class="edit">
            <input type="button" value="删除" class="delete">
        </td>
    </tr>
    <tr>
        <td>2</td>
        <td>Alex</td>
        <td>吹牛逼</td>
        <td>
            <input type="button" value="编辑" class="edit">
            <input type="button" value="删除" class="delete">
        </td>
    </tr>
    <tr>
        <td>3</td>
        <td>苑昊</td>
        <td>不洗头</td>
        <td>
            <input type="button" value="编辑" class="edit">
            <input type="button" value="删除" class="delete">
        </td>
    </tr>

    </tbody>
</table>


<div class="cover hide"></div>
<div class="modal hide">
    <p><input type="text" id="username"></p>
    <p><input type="text" id="hobby"></p>
    <p>
        <button id="submit">提交</button>
        <button id="cancel">取消</button>
    </p>
</div>

<script src="jquery-3.3.1.min.js"></script>
<script>

    // 定义一个隐藏模态框的函数
    function hideModal() {
        $(".cover, .modal").addClass("hide");
    }

    function showModal() {
        $(".cover, .modal").removeClass("hide");
    }

    $("#add").click(function () {
        // 点击新增按钮要做的事儿
        // 1. 弹出模态框
        showModal();
    });


    $("#submit").click(function () {
        // 点击提交按钮要做的事儿
        // 1. 取值,取模态框中用户填写的值
        let username = $("#username").val();
        let hobby = $("#hobby").val();

        // 2. 隐藏模态框
        hideModal();

        // 需要作判断
        // 如果是新增操作
        // $().data("tr") 返回值如果是undefined就表示 不是编辑操作

            // 3. 创建tr标签, 追加td, 要拼接序号和用户填写的信息
            let trEle = document.createElement("tr");
            let td1 = document.createElement("td");
            td1.innerText = $("table tr").length;
            $(trEle).append(td1);
            let td2 = document.createElement("td");
            td2.innerText = username;
            $(trEle).append(td2);
            let td3 = document.createElement("td");
            td3.innerText = hobby;
            $(trEle).append(td3);
            // clone
    //        $("table td").last().clone().appendTo(trEle);
            let td4 = document.createElement("td");
            td4.innerHTML = `
               <input type="button" value="编辑" class="edit">
               <input type="button" value="删除" class="delete">
    `;
            $(trEle).append(td4);
            // 4. 追加到table tbody标签的最后
            $("tbody").append(trEle);

        // 如果是编辑操作
            // 拿到用户编辑之后的值 ,要将编辑的当前行指定位置的数据更新一下
            // 从 .data()中取出之前保存的 那一行


    });


//    $("#cancel").click(function () {
//        // 点击取消
//        // 1. 把模态框隐藏
//        hideModal();
//        // 2. 把之前填写的清空掉
//        $("#username, #hobby").val("");
//    });

    $("#cancel").on("click", function () {
        // 点击取消
        // 1. 把模态框隐藏
        hideModal();
        // 2. 把之前填写的清空掉
        $("#username, #hobby").val("");
    });


//    $(".delete").click(function () {
//        // 删除按钮点击要做的事儿
//        // 1.更新序号...
//        // 把当前行后面的所有tr的第一个td的值-1
//        let $currentTr = $(this).parent().parent();
//        let $nextAllTr = $currentTr.nextAll();
//        for (let i = 0; i < $nextAllTr.length; i++) {
//            let n = $($nextAllTr[i]).children().first().text();
//            $($nextAllTr[i]).children().first().text(n - 1);
//        }
//        // 2. 把当前点击按钮所在的行 删掉
//        $currentTr.remove();
//    });

    // 事件委托
    $("table").on("click", ".delete", function () {
        // 删除按钮点击要做的事儿
        // 1.更新序号...
        // 把当前行后面的所有tr的第一个td的值-1
        let $currentTr = $(this).parent().parent();
        let $nextAllTr = $currentTr.nextAll();
        for (let i = 0; i < $nextAllTr.length; i++) {
            let n = $($nextAllTr[i]).children().first().text();
            $($nextAllTr[i]).children().first().text(n - 1);
        }
        // 2. 把当前点击按钮所在的行 删掉
        $currentTr.remove();
    });


    // 点击编辑按钮要做的事儿
    $("table").on("click", ".edit", function () {
        // 弹出模态框
        showModal();
        // 取到 点击的编辑按钮 那一行的值 填充到模态框的input中
        // this  --> 当前点击的编辑按钮

        // 把当前编辑的这一行 jQuery对象 保存到.data("tr", $())里面
    })

</script>
</body>
</html>
View Code

 

 

 

猜你喜欢

转载自www.cnblogs.com/maojiang/p/9145819.html