day 57 jQuery的补充

.data()

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

.data(key, value):

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

注意    value  可以是任意数据  可以是值,也可以是jQuery对象等

$("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对应的数据

示例:

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

需要注意的点

//<td>内容</td>要想取出这里边的内容是用 .text() 放法, 想要取出输入框中(如 <input type='text' >)的内容是用.val() 

第二:可以在一个事件中给一个全局的元素上存储相应的值用  .data('key','想要存的内容,可以是值,也可以是一个对象') ,然后在另外一个事件中就可以钓鱼那个这个全局元素中

存储的对象  

  如:在列表中的编辑事件中将被选中编辑的行  作为一个value 存到全局的tbody中去,这样就可以通过在弹出模态框时判断我这个key中是否有值
而确认我的触发模态框弹出的事件是编辑还是新增, 如果是编辑的话就讲刚存入的对象取出并直接对他的第几个内容中的 .text()值进行修改

        编辑事件中的操作
      //被选中的行的children组成的列表 var $tobianlist = $(this).parent().parent().children(); //被选中的行的列表放到一个全局变量的val中去,这样可以在另外一个触发的事件中去取出这个列表 $('tbody').data('key',$tobianlist );


        确定事件中的操作
      
       var $tobianlist=$('tbody').data('key');
       if ($tobianlist===undefined){

      else{$tobianlist.eq(1).text($('.n1').val());
       $tobianlist.eq(2).text($('.n2').val());
     

具体实现表格的编辑功能的代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文档操作示例</title>
    <style>
        .cover {
            position: fixed;
            top: 0;
            left: 0;
            bottom: 0;
            right: 0;
            background-color: rgba(0, 0, 0, 0.3);
            z-index: 999;
        }

        .modal {
            position: fixed;
            top: 50%;
            left: 50%;
            height: 300px;
            width: 500px;
            margin-left: -250px;
            margin-top: -150px;
            background-color: white;
            z-index: 1000;
        }

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

<button id="b1">新增</button>
<table border="1" id="t1">
    <thead>
    <tr>
        <th>#</th>
        <th>姓名</th>
        <th>爱好</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td>1</td>
        <td>Egon</td>
        <td>杠娘</td>
        <td>
            <input class="bianji" type="button" value="编辑">
            <input class="delete" type="button" value="删除">
        </td>
    </tr>
    <tr>
        <td>2</td>
        <td>Alex</td>
        <td>吹牛逼</td>
        <td>
            <input class="bianji" type="button" value="编辑">
            <input class="delete" type="button" value="删除">
        </td>
    </tr>
    <tr>
        <td>3</td>
        <td>Yuan</td>
        <td>日天</td>
        <td>
            <input class="bianji" type="button" value="编辑">
            <input class="delete" type="button" value="删除">
        </td>
    </tr>
    </tbody>
    <div class="cover hide"></div>
    <div class="modal hide">
        <span>姓名<input class="n1" type="text" name="name"></span>
        <span>爱好<input class="n2" type="text" name="hobby"></span>
        <input type="button" value="确定">
        <input type="button" value="取消">
    </div>
</table>
<script src="jquery-3.2.1.min.js"></script>
<script>
    $(document).ready(function () {
        function showmodal() {
            $('.cover').toggleClass('hide').next('div').toggleClass('hide')
        }

        //新增弹出模态框
        $('#b1').on('click', function () {
            showmodal();
               $('.n1').val('');

            $('.n2').val('');
        });
        //取消关闭模态框
        $('input[value="取消"]').on('click', function () {
            showmodal()
        });
        //确定将新增的内容放进去
        $('input[value="确定"]').on('click', function () {
            var $tobianlist=$('tbody').data('key');
            if ($tobianlist===undefined){


            var newtrelem = document.createElement('tr');
            //找出序号,即当前的长度

            var xuhao = $('tbody').children().length + 1;
            var mingzi = $('.n1').val();
            var aihao = $('.n2').val();
            var innertext = '<td>' + xuhao + '</td>' + '<td>' + mingzi + '</td>' + '<td>' + aihao + '</td>';
            newtrelem.innerHTML = innertext;
            console.log(newtrelem.html);
            var neibutton = $('tbody').children().first().children().last().clone();
            $(newtrelem).append(neibutton);

            $('tbody').append(newtrelem);

            }
            else{$tobianlist.eq(1).text($('.n1').val());
            $tobianlist.eq(2).text($('.n2').val());

            }
            showmodal()

        });
        //删除
        $('tbody').on('click', '.delete', function () {
//                console.log(event.target);
            //
            var $xinIndex = $(this).parent().parent().nextAll();
//                console.log($xinIndex);
            $.each($xinIndex, function () {

                var xu = $(this).children(':first').text() - 1;
                console.log(xu);

                $(this).children(':first').text(xu);
            });
            $(this).parent().parent().remove();

        });
        //编辑
//         $('.n1').val('alexaaa');
        $('tbody').on('click', '.bianji', function () {

            showmodal();
//            $('.n1').val('');
//            $('.n2').val('');
            //被选中的行的children组成的列表
            var $tobianlist = $(this).parent().parent().children();
            //被选中的行的列表放到一个全局变量的val中去,这样可以在另外一个触发的事件中去取出这个列表
            $('tbody').data('key',$tobianlist );
            console.log($tobianlist.eq(1).text());
            //找出以前的姓名框中的内容

            //在弹出的框中显示之前的内容
            $('.n1').val($tobianlist.eq(1).text());

            //弹出的框中显示当前的爱好内容
            //<td>内容</td>要想这里边的内容是用 .text() 放法,  想要取出输入框中(如 <input  type='text' >)的内容是用.val()
            $('.n2').val($tobianlist.eq(2).text());

            //去到提交的地方将新内容替换进去



        })

    });


</script>

</body>
</html>
View Code

 

插件

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()();)   这样即保证了新推展的插件可以被引用,还可以将函数封装在插件里边,以免同时引用多个插件的时候出现同名的函数导致函数被覆盖(作用域空间在函数里,不是全局,所以不会被覆盖)
(function($){ $.extend({ funcName:function(){ ... }, }); })(jQuery);

例子

登录验证

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录校验jQuery版</title>
    <style>
        .error {
            color: red;
        }
    </style>
</head>
<body>

<form action="" novalidate>
    <div>
        <label for="name">姓名</label>
        <input id="name" type="text" name="username" egon="true" autocomplete="off">
        <span class="error"></span>
    </div>
    <div>
        <label for="pwd">密码</label>
        <input id="pwd" type="password" name="password" egon="true" autocomplete="off">
        <span class="error"></span>
    </div>
    <div>
        <label for="mobile">手机</label>
        <input id="mobile" type="text" name="mobile" egon="true" autocomplete="off">
        <span class="error"></span>
    </div>
    <div>
        <label for="address">地址</label>
        <input id="address" type="text" name="address" autocomplete="off">
        <span class="error"></span>
    </div>
    <div>
        <input id="submit" type="submit" value="登录">
    </div>
</form>
<script src="../jquery-3.2.1.min.js"></script>
<script src="02-checkPlugin.js"></script>
<!--下面引用很多很多别人写好的jQuery插件-->
<script>
    $.validate();
</script>

</body>
</html>
登录验证代码

插件代码

/**
 * Created by Administrator on 2018/1/5.
 */


(function ($) {
    $.extend({
        validate: function () {
            check();//写的函数被封装在自执行函数里边,然后被新增的插件调用
        }
    });
    function check() {
    $("form :submit").on("click", function () {
        // 先把上一次的错误提示信息清空
        $("form span.error").text("");
        // 设置一个阻止submit默认提交事件执行的标志位
        var flag = true;
        // 开始校验
        // 1. 找到所有要填写的input
        $("form input[type!='submit']").each(function () {
            // this 指的是具体的每一个input
            var inputName = $(this).attr("name");
            // 取input的值
            var inputValue = $(this).val();
            // 取出当前input筐的label文本
            var inputLabel = $(this).prev().text();
            var errMsg;  // 提前申明一个错误信息的变量
            // 1.5 只有必填项才做校验
            if ($(this).attr("egon")) {
                // 是必填项
                // 2. 针对inputVlaue做判断
                if (inputValue.length === 0) {
                    // 当前这个input没有值
                    errMsg = inputLabel + "不能为空";
                    // 把错误信息填到span标签中
                    $(this).next().text(errMsg);
                    flag = false;
                    return false;  // 跳出each循环
                }
                // 如果这个input筐是password,需要多做一个判断:密码位数不能少于6位
                if (inputName === "password") {
                    if (inputValue.length < 6) {
                        errMsg = inputLabel + "不能少于6位";
                        // 把错误信息填到span标签中
                        $(this).next().text(errMsg);
                        flag = false;
                        return false;  // 跳出each循环
                    }
                }
                // 如果inpur框是mobile,需要加一个判断|:判断手机号是不是合法的手机号
                if (inputName === "mobile") {
                    if (!/^1[345678]\d{9}$/.test(inputValue)) {
                        errMsg = inputLabel + "格式不正确";
                        // 把错误信息填到span标签中
                        $(this).next().text(errMsg);
                        flag = false;
                        return false;  // 跳出each循环
                    }
                }
            }
        });
        return flag;
    })
}
})(jQuery);
View Code

 

posted on 2018-01-06 14:06  王大拿  阅读(172)  评论(0编辑  收藏  举报

导航