jQuery基础之三(事件操做)

一:经常使用事件

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

keydown和keyup事件组合示例:css

<!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>
</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.2.1.min.js"></script>
<script>
  // 全选
  $("#b1").on("click", function () {
    $(":checkbox").prop("checked", true);
  });
  // 取消
  $("#b2").on("click", function () {
    $(":checkbox").prop("checked", false);
  });
  // 反选
  $("#b3").on("click", function () {
    $(":checkbox").each(function () {
      var flag = $(this).prop("checked");
      $(this).prop("checked", !flag);
    })
  });
  // 按住shift键,批量操做
  // 定义全局变量
  var flag = false;
  // 全局事件,监听键盘shift按键是否被按下
  $(window).on("keydown", function (e) {
//    alert(e.keyCode);
    if (e.keyCode === 16){
      flag = true;
    }
  });
  // 全局事件,shift按键抬起时将全局变量置为false
  $(window).on("keyup", function (e) {
    if (e.keyCode === 16){
      flag = false;
    }
  });
  // select绑定change事件
  $("table select").on("change", function () {
    // 是否为批量操做模式
    if (flag) {
      var selectValue = $(this).val();
      // 找到全部被选中的那一行的select,选中指定值
      $("input:checked").parent().parent().find("select").val(selectValue);
    }
  })
</script>
</body>
</html>
View Code

hover事件示例html

<!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>hover示例</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }
    .nav {
      height: 40px;
      width: 100%;
      background-color: #3d3d3d;
      position: fixed;
      top: 0;
    }

    .nav ul {
      list-style-type: none;
      line-height: 40px;
    }

    .nav li {
      float: left;
      padding: 0 10px;
      color: #999999;
      position: relative;
    }
    .nav li:hover {
      background-color: #0f0f0f;
      color: white;
    }

    .clearfix:after {
      content: "";
      display: block;
      clear: both;
    }

    .son {
      position: absolute;
      top: 40px;
      right: 0;
      height: 50px;
      width: 100px;
      background-color: #00a9ff;
      display: none;
    }

    .hover .son {
      display: block;
    }
  </style>
</head>
<body>
<div class="nav">
  <ul class="clearfix">
    <li>登陆</li>
    <li>注册</li>
    <li>购物车
      <p class="son hide">
        空空如也...
      </p>
    </li>
  </ul>
</div>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script>
$(".nav li").hover(
  function () {
    $(this).addClass("hover");
  },
  function () {
    $(this).removeClass("hover");
  }
);
</script>
</body>
</html>
View Code

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

<!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>
View Code

二:事件绑定与移除

绑定事件方法:web

$(object).on( events [, selector ],function(){})

移除事件方法:正则表达式

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

补充:阻止后续事件执行数组

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

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

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

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

三:页面载入

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

两种写法:工具

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

简写(不推荐使用):

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

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

<!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>
    .error {
      color: red;
    }
  </style>
</head>
<body>

<form id="myForm">
  <label for="name">姓名</label>
  <input type="text" id="name">
  <span class="error"></span>
  <label for="passwd">密码</label>
  <input type="password" id="passwd">
  <span class="error"></span>
  <input type="submit" id="modal-submit" value="登陆">
</form>

<script src="jquery-3.2.1.min.js"></script>
<script src="s7validate.js"></script>
<script>
  function myValidation() {
    // 屡次用到的jQuery对象存储到一个变量,避免重复查询文档树
    var $myForm = $("#myForm");
    $myForm.find(":submit").on("click", function () {
      // 定义一个标志位,记录表单填写是否正常
      var flag = true;
      $myForm.find(":text, :password").each(function () {
        var val = $(this).val();
        if (val.length <= 0 ){
          var labelName = $(this).prev("label").text();
          $(this).next("span").text(labelName + "不能为空");
          flag = false;
        }
      });
      // 表单填写有误就会返回false,阻止submit按钮默认的提交表单事件
      return flag;
    });
    // input输入框获取焦点后移除以前的错误提示信息
    $myForm.find("input[type!='submit']").on("focus", function () {
      $(this).next(".error").text("");
    })
  }
  // 文档树就绪后执行
  $(document).ready(function () {
    myValidation();
  });
</script>
</body>
</html>
View Code

四:事件委托

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

示例:

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

$("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])

自定义动画示例:

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

jQuery.each(collection, callback(indexInArray, valueOfElement)):

描述:一个通用的迭代函数,它能够用来无缝迭代对象和数组。数组和相似数组的对象经过一个长度属性(如一个函数的参数对象)来迭代数字索引,从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对应的数据

插件(了解内容)

jQuery.extend(object)

jQuery的命名空间下添加新的功能。多用于插件开发者向 jQuery 中添加新函数时使用。

示例:

<script>
jQuery.extend({
  min:function(a, b){return a < b ? a : b;},
  max:function(a, b){return a > b ? a : b;}
});
jQuery.min(2,3);// => 2
jQuery.max(4,5);// => 5
</script>

jQuery.fn.extend(object)

一个对象的内容合并到jQuery的原型,以提供新的jQuery实例方法。

<script>
  jQuery.fn.extend({
    check:function(){
      return this.each(function(){this.checked =true;});
    },
    uncheck:function(){
      return this.each(function(){this.checked =false;});
    }
  });
// jQuery对象能够使用新添加的check()方法了。
$("input[type='checkbox']").check();
</script>

单独写在文件中的扩展:

(function(jq){
  jq.extend({
    funcName:function(){
    ...
    },
  });
})(jQuery);

jQuery登陆验证插件示例

<!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>登陆校验示例</title>
  <style>
    .login-form {
      margin: 100px auto 0;
      max-width: 330px;
    }
    .login-form > div {
      margin: 15px 0;
    }
    .error {
      color: red;
    }
  </style>
</head>
<body>


<div>
  <form action="" class="login-form" novalidate>

    <div>
      <label for="username">姓名</label>
      <input id="username" type="text" name="name" required autocomplete="off">
      <span class="error"></span>
    </div>
    <div>
      <label for="passwd">密码</label>
      <input id="passwd" type="password" name="password" required autocomplete="off">
      <span class="error"></span>
    </div>
    <div>
      <label for="mobile">手机</label>
      <input id="mobile" type="text" name="mobile" required autocomplete="off">
      <span class="error"></span>
    </div>
    <div>
      <label for="where">来自</label>
      <input id="where" type="text" name="where" autocomplete="off">
      <span class="error"></span>
    </div>
    <div>
      <input type="submit" value="登陆">
    </div>

  </form>
</div>

<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script src="validate.js"></script>
<script>
  $.validate();
</script>
</body>
</html>
HTML文件
"use strict";
(function ($) {
  function check() {
    // 定义一个标志位,表示验证经过仍是验证不经过
    var flag = true;
    var errMsg;
    // 校验规则
    $("form input[type!=':submit']").each(function () {
      var labelName = $(this).prev().text();
      var inputName = $(this).attr("name");
      var inputValue = $(this).val();
      if ($(this).attr("required")) {
        // 若是是必填项
        if (inputValue.length === 0) {
          // 值为空
          errMsg = labelName + "不能为空";
          $(this).next().text(errMsg);
          flag = false;
          return false;
        }
        // 若是是密码类型,咱们就要判断密码的长度是否大于6位
        if (inputName === "password") {
          // 除了上面判断为不为空还要判断密码长度是否大于6位
          if (inputValue.length < 6) {
            errMsg = labelName + "必须大于6位";
            $(this).next().text(errMsg);
            flag = false;
            return false;
          }
        }
        // 若是是手机类型,咱们须要判断手机的格式是否正确
        if (inputName === "mobile") {
          // 使用正则表达式校验inputValue是否为正确的手机号码
          if (!/^1[345678]\d{9}$/.test(inputValue)) {
            // 不是有效的手机号码格式
            errMsg = labelName + "格式不正确";
            $(this).next().text(errMsg);
            flag = false;
            return false;
          }
        }
      }
    });
    return flag;
  }

  function clearError(arg) {
    // 清空以前的错误提示
    $(arg).next().text("");
  }
  // 上面都是我定义的工具函数
  $.extend({
    validate: function () {
      $("form :submit").on("click", function () {
      return check();
    });
    $("form :input[type!='submit']").on("focus", function () {
      clearError(this);
    });
    }
  });
})(jQuery);
JS文件

传参版

<!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>登陆校验示例</title>
  <style>
    .login-form {
      margin: 100px auto 0;
      max-width: 330px;
    }
    .login-form > div {
      margin: 15px 0;
    }
    .error {
      color: red;
    }
  </style>
</head>
<body>


<div>
  <form action="" class="login-form" novalidate>

    <div>
      <label for="username">姓名</label>
      <input id="username" type="text" name="name" required autocomplete="off">
      <span class="error"></span>
    </div>
    <div>
      <label for="passwd">密码</label>
      <input id="passwd" type="password" name="password" required autocomplete="off">
      <span class="error"></span>
    </div>
    <div>
      <label for="mobile">手机</label>
      <input id="mobile" type="text" name="mobile" required autocomplete="off">
      <span class="error"></span>
    </div>
    <div>
      <label for="where">来自</label>
      <input id="where" type="text" name="where" autocomplete="off">
      <span class="error"></span>
    </div>
    <div>
      <input type="submit" value="登陆">
    </div>

  </form>
</div>

<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script src="validate3.js"></script>
<script>
  $.validate({"name":{"required": true}, "password": {"required": true, "minLength": 8}, "mobile": {"required": true}});
</script>
</body>
</html>
HTML文件
"use strict";
(function ($) {
  function check(arg) {
    // 定义一个标志位,表示验证经过仍是验证不经过
    var flag = true;
    var errMsg;
    // 校验规则
    $("form input[type!=':submit']").each(function () {
      var labelName = $(this).prev().text();
      var inputName = $(this).attr("name");
      var inputValue = $(this).val();
      if (arg[inputName].required) {
        // 若是是必填项
        if (inputValue.length === 0) {
          // 值为空
          errMsg = labelName + "不能为空";
          $(this).next().text(errMsg);
          flag = false;
          return false;
        }
        // 若是是密码类型,咱们就要判断密码的长度是否大于6位
        if (inputName === "password") {
          // 除了上面判断为不为空还要判断密码长度是否大于6位
          if (inputValue.length < arg[inputName].minLength) {
            errMsg = labelName + "必须大于"+arg[inputName].minLength+"位";
            $(this).next().text(errMsg);
            flag = false;
            return false;
          }
        }
        // 若是是手机类型,咱们须要判断手机的格式是否正确
        if (inputName === "mobile") {
          // 使用正则表达式校验inputValue是否为正确的手机号码
          if (!/^1[345678]\d{9}$/.test(inputValue)) {
            // 不是有效的手机号码格式
            errMsg = labelName + "格式不正确";
            $(this).next().text(errMsg);
            flag = false;
            return false;
          }
        }
      }
    });
    return flag;
  }

  function clearError(arg) {
    // 清空以前的错误提示
    $(arg).next().text("");
  }
  // 上面都是我定义的工具函数
  $.extend({
    validate: function (arg) {
      $("form :submit").on("click", function () {
      return check(arg);
    });
    $("form :input[type!='submit']").on("focus", function () {
      clearError(this);
    });
    }
  });
})(jQuery);
JS文件
相关文章
相关标签/搜索