前端开发之jQuery

本文详细介绍了jQuery的核心概念,包括jQuery简介、选择器和筛选器的使用、元素的操作(属性、CSS和文档处理)、事件处理、动画效果以及文件上传的三种方法。jQuery是一个高效、易用的JavaScript库,简化了DOM操作,提供了丰富的API和插件支持。
摘要由CSDN通过智能技术生成

一、jquery简介

1. jquery是什么?

  • jQuery由美国人John Resig创建,至今已吸引了来自世界各地的众多 javascript高手加入其team。
  • jQuery是继prototype之后又一个优秀的Javascript框架。其宗旨是——WRITE LESS,DO MORE,写更少的代码,做更多的事情。
  • 它是轻量级的js库(压缩后只有21k) ,这是其它的js库所不及的,它兼容CSS3,还兼容各种浏览器 (IE 6.0+, FF 1.5+, Safari 2.0+, Opera 9.0+)。
  • jQuery是一个快速的,简洁的javaScript库,使用户能更方便地处理HTML documents、events、实现动画效果,并且方便地为网站提供AJAX交互。
  • jQuery还有一个比较大的优势是,它的文档说明很全,而且各种应用也说得很详细,同时还有许多成熟的插件可供选择。
  • jQuery能够使用户的html页保持代码和html内容分离,也就是说,不用再在html里面插入一堆js来调用命令了,只需定义id即可。

2. 什么是jQuery对象?

  • jQuery 对象就是通过jQuery包装DOM对象后产生的对象。

  • jQuery 对象是 jQuery 独有的. 如果一个对象是 jQuery 对象, 那么它就可以使用 jQuery 里的方法: $(“#test”).html(); 比如:$("#test").html() 意思是指:获取ID为test的元素内的html代码。其中html()是jQuery里的方法,这段代码等同于用DOM实现代码: document.getElementById(" test ").innerHTML;

  • 虽然jQuery对象是包装DOM对象后产生的,但是jQuery无法使用DOM对象的任何方法,同理DOM对象也不能使用jQuery里的方法.乱使用会报错。约定:如果获取的是 jQuery 对象, 那么要在变量前面加上$。

    var $variable = jQuery 对象
    var variable = DOM 对象

  • 基本语法:$(selector).action()

二、寻找元素(重要的选择器和筛选器)

1. 选择器

  • 基本选择器 $("*") $("#id") $(".class") $(“element”) $(".class,p,div")
  • 层级选择器 $(".outer div") $(".outer>div") $(".outer+div") $(".outer~div")
  • 基本筛选器 $(“li:first”) $(“li:eq(2)”) $(“li:even”) $(“li:gt(1)”)
  • 属性选择器 $(’[id=“div1”]’) $(’["alex=“sb”][id]’)
  • 表单选择器 $("[type=‘text’]")----->$(":text") 注意只适用于input标签
    $(“input:checked”)

2. 筛选器

  • 过滤筛选器

    $(“li”).eq(2) $(“li”).first() $(“ul li”).hasclass(“test”)

  • 查找筛选器

    $(“div”).children(".test") $(“div”).find(".test")

    $(".test").next() $(".test").nextAll() $(".test").nextUntil()

    $(“div”).prev() $(“div”).prevAll() $(“div”).prevUntil()

    $(".test").parent() $(".test").parents() $(".test").parentUntil()

    $(“div”).siblings()

实例:左侧菜单

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>left_menu</title>
    <script src="js/jquery-2.2.3.js"></script>
    <script>
          function show(self){
//              console.log($(self).text())
              $(self).next().removeClass("hide")
              $(self).parent().siblings().children(".con").addClass("hide")
          }
    </script>
    <style>
          .menu{
              height: 500px;
              width: 30%;
              background-color: gainsboro;
              float: left;
          }
          .content{
              height: 500px;
              width: 70%;
              background-color: rebeccapurple;
              float: left;
          }
         .title{
             line-height: 50px;
             background-color: #425a66;
             color: forestgreen;}
         .hide{
             display: none;
         }
    </style>
</head>
<body>
<div class="outer">
    <div class="menu">
        <div class="item">
            <div class="title" onclick="show(this);">菜单一</div>
            <div class="con">
                <div>111</div>
                <div>111</div>
                <div>111</div>
            </div>
        </div>
        <div class="item">
            <div class="title" onclick="show(this);">菜单二</div>
            <div class="con hide">
                <div>111</div>
                <div>111</div>
                <div>111</div>
            </div>
        </div>
        <div class="item">
            <div class="title" onclick="show(this);">菜单三</div>
            <div class="con hide">
                <div>111</div>
                <div>111</div>
                <div>111</div>
            </div>
        </div>
    </div>
    <div class="content"></div>
</div>
</body>
</html>

实例:tab切换

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>tab</title>
    <script src="js/jquery-2.2.3.js"></script>
    <script>
           function tab(self){
               var index=$(self).attr("xxx")
               $("#"+index).removeClass("hide").siblings().addClass("hide")
               $(self).addClass("current").siblings().removeClass("current")
           }
    </script>
    <style>
        *{
            margin: 0px;
            padding: 0px;
        }
        .tab_outer{
            margin: 0px auto;
            width: 60%;
        }
        .menu{
            background-color: #cccccc;
            /*border: 1px solid red;*/
            line-height: 40px;
        }
        .menu li{
            display: inline-block;
        }
        .menu a{
            border-right: 1px solid red;
            padding: 11px;
        }
        .content{
            background-color: tan;
            border: 1px solid green;
            height: 300px;
        }
        .hide{
            display: none;
        }
        .current{
            background-color: darkgray;
            color: yellow;
            border-top: solid 2px rebeccapurple;
        }
    </style>
</head>
<body>
      <div class="tab_outer">
          <ul class="menu">
              <li xxx="c1" class="current" onclick="tab(this);">菜单一</li>
              <li xxx="c2" onclick="tab(this);">菜单二</li>
              <li xxx="c3" onclick="tab(this);">菜单三</li>
          </ul>
          <div class="content">
              <div id="c1">内容一</div>
              <div id="c2" class="hide">内容二</div>
              <div id="c3" class="hide">内容三</div>
          </div>
      </div>
</body>
</html>

三、操作元素(属性 CSS 和 文档处理)

1. 属性操作

  • $(“p”).text() $(“p”).html() $(":checkbox").val()
  • $(".test").attr(“alex”) $(".test").attr(“alex”,“sb”)
  • $(".test").attr(“checked”,“checked”) $(":checkbox").removeAttr(“checked”)
  • $(".test").prop(“checked”,true)
  • $(".test").addClass(“hide”)

实例:编辑框正反选

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-2.2.3.js"></script>
    <script>
             function selectall(){
                 $("table :checkbox").prop("checked",true)
             }
             function che(){
                 $("table :checkbox").prop("checked",false)
             }
             function reverse(){
//                 var idlist=$("table :checkbox")
//                 for(var i=0;i<idlist.length;i++){
//                     var element=idlist[i];
//                     var ischecked=$(element).prop("checked")
//                     if (ischecked){
//                         $(element).prop("checked",false)
//                     }
//                     else {
//                         $(element).prop("checked",true)
//                     }
//                 }
                 $("table :checkbox").each(function(){
                     if ($(this).prop("checked")){
                         $(this).prop("checked",false)
                     }
                     else {
                         $(this).prop("checked",true)
                     }
                 });
//                 li=[10,20,30,40]
                 dic={name:"yuan",sex:"male"}
//                 $.each(li,function(i,x){
//                     console.log(i,x)
//                 })
             }
    </script>
</head>
<body>
     <button onclick="selectall();">全选</button>
     <button onclick="che();">取消</button>
     <button onclick="reverse();">反选</button>
     <table border="1">
         <tr>
             <td><input type="checkbox"></td>
             <td>111</td>
         </tr>
         <tr>
             <td><input type="checkbox"></td>
             <td>222</td>
         </tr>
         <tr>
             <td><input type="checkbox"></td>
             <td>333</td>
         </tr>
         <tr>
             <td><input type="checkbox"></td>
             <td>444</td>
         </tr>
     </table>
</body>
</html>

实例:模态对话框

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>批量编辑</title>
        <!--<link rel="stylesheet" href="css/mycss.css" />-->
        <style>
            *{
    margin: 0;
    padding: 0;
}
body {
  font-family: 'Open Sans', sans-serif;
  font-weight: 300;
  line-height: 1.42em;
  color:rebeccapurple;
  background-color:goldenrod;
}
h1 {
  font-size:3em;
  font-weight: 300;
  line-height:1em;
  text-align: center;
  color: #4DC3FA;
}
.blue {
    color: #185875;
}
.yellow {
    color: #FFF842;
    }
/*!*弹出层罩子*!*/
#full {
    background-color:gray;
    left:0;
    opacity:0.7;
    position:absolute;
    top:0;
    filter:alpha(opacity=30);
}
.modified {
    background-color: #1F2739;
    border:3px solid whitesmoke;
    height:400px;
    left:50%;
    margin:-200px 0 0 -200px;
    padding:1px;
    position:fixed;
    /*position:absolute;*/
    top:50%;
    width:400px;
    display:none;
}
li {
    list-style: none;
    margin: 20px 0 0 50px;
    color: #FB667A;
}
input[type="text"] {
  padding: 10px;
  border: solid 1px #dcdcdc;
  /*transition: box-shadow 3s, border 3s;*/
}
.iputbutton {
    margin: 60px 0 0 50px;
    color: whitesmoke;
    background-color: #FB667A;
    height: 30px;
    width: 100px;
    border: 1px dashed;
}
.container th h1 {
    font-weight: bold;
    font-size: 1em;
      text-align: left;
      color: #185875;
}
.container td {
    font-weight: normal;
    font-size: 1em;
}
.container {
    width: 80%;
    margin: 0 auto;
}
.container td, .container th {
    padding-bottom: 2%;
    padding-top: 2%;
      padding-left:2%;
}
/*单数行*/
.container tr:first-child {
    background-color: red;
}
/*偶数行*/
.container tr:not(first-child){
      background-color: cyan;
}
.container th {
    background-color: #1F2739;
}
.container td:last-child {
    color: #FB667A;
}
/*鼠标进过行*/
.container tr:hover {
   background-color: #464A52;
}
/*鼠标进过列*/
.container td:hover {
  background-color: #FB667A;
  color: #403E10;
  font-weight: bold;
  transform: translate3d(5px, -5px, 0);
}
        </style>
        <script src="jquery-2.2.3.js"></script>
        <script>
            //点击【编辑】显示
$(function () {
    $("table[name=host] tr:gt(0) td:last-child").click(function (event) {
        alert("234");
//        $("#full").css({height:"100%",width:"100%"});
        $(".modified").data('current-edit-obj', $(this));
        $(".modified,#full").show();
        var hostname = $(this).siblings("td[name=hostname]").text();
        $(".modified #hostname").val(hostname);
        var ip = $(this).siblings("td[name=ip]").text();
        $(".modified #ip").val(ip);
        var port = $(this).siblings("td[name=port]").text();
        $(".modified #port").val(port);
    });
    //取消编辑
    $(".modified #cancel").bind("click", function () {
        $(".modified,#full").hide();
    });
//    确定修改
    $(".modified #ok").bind("click", function (event) {
        var check_status = true;
        var ths = $(".modified").data('current-edit-obj');
        var hostname = $(".modified #hostname").val().trim();
        var ip = $(".modified #ip").val().trim();
        var port = $(".modified #port").val().trim();
        var port = parseInt(port);
        console.log(port);
        //        端口为空设置为22
        if (isNaN(port)) {
            alert("您没有设置正常的SSH端口号,将采用默认22号端口");
            var port = 22;
        }else if ( port > 65535) {
        //            如果端口不是一个数字 或者端口大于65535
            var check_status = false;
            $(".modified #port").css("border-color","red");
            alert("端口号超过范围!")
        };
        // 主机和ip不能是空
        if ( hostname == ""){
            var check_status = false;
            $(".modified #hostname").css("border-color","red");
        }else if (ip == "") {
            var check_status = false;
            $(".modified #ip").css("border-color","red");
        };
        if (check_status == false){
            return false;
        }else{
            //$(this).css("height","60px")   为什么不用$(this),而用$()
            $(ths).siblings("td[name=hostname]").text(hostname);
            $(ths).siblings("td[name=ip]").text(ip);
            $(ths).siblings("td[name=port]").text(port);
            $(".modified,#full").hide();
        };
    });
});          
        </script>
    </head>
    <body>
        <h1>
            <span class="blue">&lt;</span>Homework1<span class="blue">&gt;</span> <span class="yellow">HostList</span>
        </h1>
        <div id="full">
            <div class="modified">
                <li>主机名:<input id="hostname" type="text" value="" />*</li>
                <li>ip地址:<input id="ip" type="text" value="" />*</li>
                <li>端口号:<input id="port" type="text" value="" />[0-65535]</li>
                    <div id="useraction">
                    <input class="iputbutton" type="button" name="确定" id="ok" value="确定"/>
                    <input class="iputbutton" type="button" name="取消" id="cancel" value="取消"/>
                    </div>
            </div>
        </div>
        <table class="container" name="host">
            <tr>
                <th><h1>主机名</h1></th>
                <th><h1>IP地址</h1></th>
                <th><h1>端口</h1></th>
                <th><h1>操作</h1></th>
            </tr>
            <tr>
                <td name="hostname">web01</td>
                <td name="ip">192.168.2.1</td>
                <td name="port">22</td>
                <td>编辑 </td>
            </tr>
            <tr>
                <td name="hostname">web02</td>
                <td name="ip">192.168.2.2</td>
                <td name="port">223</td>
                <td>编辑 </td>
            </tr>
            <tr>
                <td name="hostname">web03</td>
                <td name="ip">192.168.2.3</td>
                <td name="port">232</td>
                <td>编辑 </td>
            </tr>
            <tr>
                <td name="hostname">web04</td>
                <td name="ip">192.168.2.4</td>
                <td name="port">232</td>
                <td>编辑 </td>
            </tr>
        </table>
    </body>
</html>

实例:从数据库存取数据实现左右移动
涉及DOM对象和jQuery对象的互相转换:

############### views ##################
def edit_teacher(request,nid):
    # 获取当前老师信息
    # 获取当前老师对应的所有班级
    # - 获取所有的班级
    # - 获取当前老师未对应的所有班级
    if request.method == "GET":
        # 当前老师的信息
        obj = models.Teacher.objects.get(id=nid)

        # 获取当前老师已经管理的所有班级
        # [ (1,"root1"),(2,"root2"),(3,"root3"),]
        obj_cls_list = obj.cls.all().values_list('id', 'caption')
        # 已经管理的班级的ID列表
        # zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象
        # 利用 * 号操作符,可以将元组解压为列表
        # >> > a = [1, 2, 3]
        # >> > b = [4, 5, 6]
        # >> > zipped = zip(a, b)  # 返回一个对象
        # >> > list(zipped)  # list() 转换为列表
        # [(1, 4), (2, 5), (3, 6)]
        
        # >> > a1, a2 = zip(*zip(a, b))  # 与 zip 相反,zip(*) 可理解为解压,返回二维矩阵式
        # >> > list(a1)
        # [1, 2, 3]
        # >> > list(a2)
        # [4, 5, 6]
        id_list = list(zip(*obj_cls_list))[0] if obj_cls_list else []
        # # [1,2,3]
        # 获取未管理的班级,
        # cls_list = models.Classes.objects.filter(id__in=id_list)
        cls_list = models.Classes.objects.exclude(id__in=id_list)
        # # 1
        return render(request, 'edit_teacher.html', {'obj': obj,
                                                     'obj_cls_list': obj_cls_list,
                                                     "cls_list": cls_list,
                                                     "id_list": id_list
                                                     })
    elif request.method == "POST":
        # nid = request.POST.get('nid')
        name = request.POST.get('name')
        cls_li = request.POST.getlist('cls')
        obj = models.Teacher.objects.get(id=nid)
        obj.name = name
        obj.save()

        obj.cls.set(cls_li)

        return redirect('/teacher.html')
################## edit_teacher.html ###################
{% extends "layout.html" %}

{% block css %}
{% endblock %}

{% block content %}
    <h1>编辑老师</h1>
    <form action="/edit_teacher-{{ obj.id }}.html" method="POST">
        <input style="display: none" type="text" id="nid" value="{{ obj.id }}" />
        <p>
            老师姓名:<input name="name" type="text" value="{{ obj.name }}" />
        </p>
        <p>
            已管理班级
            <select id="sel" name="cls" multiple>
                {% for row in obj_cls_list %}
                    <option value="{{ row.0 }}">{{ row.1 }}</option>
                {% endfor %}
            </select>
            未管理班级:
            <select id="none" multiple>
                {% for row in cls_list %}
                    <option value="{{ row.id }}">{{ row.caption }}</option>
                {% endfor %}
            </select>
        </p>
        <div>
            <a id="removeCls"> >> </a>
            <a id="addCls"> << </a>
        </div>
        <input id="submit_form" type="submit" value="提交" />
    </form>
{% endblock %}


{% block js %}
    <script>
        $(function () {
            $('#menu_teacher').addClass('active');
            bindRemoveCls();
            bindAddCls();
            bindSubmitForm();
        });
        function bindSubmitForm(){
            $('#submit_form').click(function () {
                // 让select中全选中
                $('#sel').children().each(function () {
                    $(this).prop('selected', true);
                })
            })
        }

        function bindRemoveCls() {
            $('#removeCls').click(function () {
                {#DOM对象的selectedOptions可以把所有选中的option拿到#}
                var options = $('#sel')[0].selectedOptions;
                while(options.length>0){
                    $(options[0]).appendTo('#none');
                }

            })
        }

        function bindAddCls() {
            $('#addCls').click(function () {
                var options = $('#none')[0].selectedOptions;
                while(options.length>0){
                    $(options[0]).appendTo('#sel');
                }

            })
        }
    </script>
{% endblock %}

2. CSS操作

  • (样式) css("{color:‘red’,backgroud:‘blue’}")
  • (位置) offset() position() scrollTop() scrollLeft()
  • (尺寸) height() width()

实例:返回顶部

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-2.2.3.js"></script>
    <script>
          window.onscroll=function(){
              var current=$(window).scrollTop();
              console.log(current)
              if (current>100){

                  $(".returnTop").removeClass("hide")
              }
              else {
              $(".returnTop").addClass("hide")
          }
          }
           function returnTop(){
//               $(".div1").scrollTop(0);
               $(window).scrollTop(0)
           }
    </script>
    <style>
        body{
            margin: 0px;
        }
        .returnTop{
            height: 60px;
            width: 100px;
            background-color: darkgray;
            position: fixed;
            right: 0;
            bottom: 0;
            color: greenyellow;
            line-height: 60px;
            text-align: center;
        }
        .div1{
            background-color: orchid;
            font-size: 5px;
            overflow: auto;
            width: 500px;
        }
        .div2{
            background-color: darkcyan;
        }
        .div3{
            background-color: aqua;
        }
        .div{
            height: 300px;
        }
        .hide{
            display: none;
        }
    </style>
</head>
<body>
     <div class="div1 div">
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
     </div>
     <div class="div2 div"></div>
     <div class="div3 div"></div>
     <div class="returnTop hide" onclick="returnTop();">返回顶部</div>
</body>
</html>

实例:滚动菜单

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        body{
            margin: 0px;
        }
        img {
            border: 0;
        }
        ul{
            padding: 0;
            margin: 0;
            list-style: none;
        }
        .clearfix:after {
            content: ".";
            display: block;
            height: 0;
            clear: both;
            visibility: hidden;
        }
        .wrap{
            width: 980px;
            margin: 0 auto;
        }
        .pg-header{
            background-color: #303a40;
            -webkit-box-shadow: 0 2px 5px rgba(0,0,0,.2);
            -moz-box-shadow: 0 2px 5px rgba(0,0,0,.2);
            box-shadow: 0 2px 5px rgba(0,0,0,.2);
        }
        .pg-header .logo{
            float: left;
            padding:5px 10px 5px 0px;
        }
        .pg-header .logo img{
            vertical-align: middle;
            width: 110px;
            height: 40px;
        }
        .pg-header .nav{
            line-height: 50px;
        }
        .pg-header .nav ul li{
            float: left;
        }
        .pg-header .nav ul li a{
            display: block;
            color: #ccc;
            padding: 0 20px;
            text-decoration: none;
            font-size: 14px;
        }
        .pg-header .nav ul li a:hover{
            color: #fff;
            background-color: #425a66;
        }
        .pg-body{
        }
        .pg-body .catalog{
            position: absolute;
            top:60px;
            width: 200px;
            background-color: #fafafa;
            bottom: 0px;
        }
        .pg-body .catalog.fixed{
            position: fixed;
            top:10px;
        }
        .pg-body .catalog .catalog-item.active{
            color: #fff;
            background-color: #425a66;
        }
        .pg-body .content{
            position: absolute;
            top:60px;
            width: 700px;
            margin-left: 210px;
            background-color: #fafafa;
            overflow: auto;
        }
        .pg-body .content .section{
            height: 500px;
        }
    </style>
</head>
<body>
    <div class="pg-header">
        <div class="wrap clearfix">
            <div class="logo">
                <a href="#">
                    <img src="images/3.jpg">
                </a>
            </div>
            <div class="nav">
                <ul>
                    <li>
                        <a  href="#">首页</a>
                    </li>
                    <li>
                        <a  href="#">功能一</a>
                    </li>
                    <li>
                        <a  href="#">功能二</a>
                    </li>
                </ul>
            </div>

        </div>
    </div>
    <div class="pg-body">
        <div class="wrap">
            <div class="catalog">
                <div class="catalog-item" auto-to="function1"><a>1</a></div>
                <div class="catalog-item" auto-to="function2"><a>2</a></div>
                <div class="catalog-item" auto-to="function3"><a>3</a></div>
            </div>
            <div class="content">
                <div menu="function1" class="section">
                    <h1>第一章</h1>
                </div>
                <div menu="function2" class="section">
                    <h1>第二章</h1>
                </div>
                <div menu="function3" class="section">
                    <h1>第三章</h1>
                </div>
            </div>
        </div>
    </div>
    <script type="text/javascript" src="js/jquery-2.2.3.js"></script>
    <script type="text/javascript">
     window.onscroll=function(){
         var ws=$(window).scrollTop()
         if (ws>50){
             $(".catalog").addClass("fixed")
         }
         else {
             $(".catalog").removeClass("fixed")
         }
         $(".content").children("").each(function(){
          var offtop=$(this).offset().top;
//             console.log(offtop)
             var total=$(this).height()+offtop;
             if (ws>offtop && ws<total){                 if($(window).height()+$(window).scrollTop()==$(document).height()){
                     var index=$(".catalog").children(" :last").css("fontSize","40px").siblings().css("fontSize","12px")
                     console.log(index)
                 target='div[auto-to="'+index+'"]';
                 $(".catalog").children(target).css("fontSize","40px").siblings().css("fontSize","12px")
                 }
                 else{
                      var index=$(this).attr("menu");
                 target='div[auto-to="'+index+'"]';               $(".catalog").children(target).css("fontSize","40px").siblings().css("fontSize","12px")
                 }
             }
         })
     }
    </script>
</body>
</html>

3. 文档处理

  • 内部插入 $("#c1").append(“hello”) $(“p”).appendTo(“div”)
    prepend() prependTo()
  • 外部插入 before() insertBefore() after insertAfter()
    replaceWith() remove() empty() clone()

实例:clone方法的应用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
      <div class="outer">
          <div class="condition">
                  <div class="icons" style="display:inline-block">
                      <a onclick="add(this);"><button>+</button></a>
                  </div>
                  <div class="input" style="display:inline-block">
                      <input type="checkbox">
                      <input type="text" value="alex">
                  </div>
          </div>
      </div>
<script src="js/jquery-2.2.3.js"></script>
    <script>
            function add(self){
                var $duplicate = $(self).parent().parent().clone();         $duplicate.find('a[οnclick="add(this);"]').attr('onclick',"removed(this)").children("").text("-");
                $duplicate.appendTo($(self).parent().parent().parent());
            }
           function removed(self){
               $(self).parent().parent().remove()
           }
    </script>
</body>
</html>

4. 事件

  • 4.1
    $(document).ready(function(){}) -----------> $(function(){})
  • 4.2
    $(“p”).click(function(){})
    $(“p”).bind(“click”,function(){})
    $(“ul”).delegate(“li”,“click”,function(){})

实例:拖动面板

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <div style="border: 1px solid #ddd;width: 600px;position: absolute;">
        <div id="title" style="background-color: black;height: 40px;color: white;">
            标题
        </div>
        <div style="height: 300px;">
            内容
        </div>
    </div>
<script type="text/javascript" src="jquery-2.2.3.js"></script>
<script>
    $(function(){
        // 页面加载完成之后自动执行
        $('#title').mouseover(function(){
            $(this).css('cursor','move');
        }).mousedown(function(e){
            //console.log($(this).offset());
            var _event = e || window.event;
            // 原始鼠标横纵坐标位置
            var ord_x = _event.clientX;
            var ord_y = _event.clientY;
            var parent_left = $(this).parent().offset().left;
            var parent_top = $(this).parent().offset().top;
            $(this).bind('mousemove', function(e){
                var _new_event = e || window.event;
                var new_x = _new_event.clientX;
                var new_y = _new_event.clientY;
                var x = parent_left + (new_x - ord_x);
                var y = parent_top + (new_y - ord_y);
                $(this).parent().css('left',x+'px');
                $(this).parent().css('top',y+'px');
            })
        }).mouseup(function(){
            $(this).unbind('mousemove');
        });
    })
</script>
</body>
</html>

实例:放大镜

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>bigger</title>
    <style>
        *{
            margin: 0;
            padding:0;
        }
        .outer{
            height: 350px;
            width: 350px;
            border: dashed 5px cornflowerblue;
        }
        .outer .small_box{
            position: relative;
        }
        .outer .small_box .float{
            height: 175px;
            width: 175px;
            background-color: darkgray;
            opacity: 0.4;
            fill-opacity: 0.4;
            position: absolute;
            display: none;
        }
        .outer .big_box{
            height: 400px;
            width: 400px;
            overflow: hidden;
            position:absolute;
            left: 360px;
            top: 0px;
            z-index: 1;
            border: 5px solid rebeccapurple;
            display: none;
        }
        .outer .big_box img{
            position: absolute;
            z-index: 5;
        }
    </style>
</head>
<body>
        <div class="outer">
            <div class="small_box">
                <div class="float"></div>
                <img src="small.jpg">
            </div>
            <div class="big_box">
                <img src="big.jpg">
            </div>
        </div>
<script src="js/jquery-2.2.3.js"></script>
<script>
    $(function(){
          $(".small_box").mouseover(function(){
              $(".float").css("display","block");
              $(".big_box").css("display","block")
          })
          $(".small_box").mouseout(function(){
              $(".float").css("display","none");
              $(".big_box").css("display","none")
          })
          $(".small_box").mousemove(function(e){
              var _event=e || window.event;
              var float_width=$(".float").width();
              var float_height=$(".float").height();
              console.log(float_height,float_width);
              var float_height_half=float_height/2;
              var float_width_half=float_width/2;
              console.log(float_height_half,float_width_half);
               var small_box_width=$(".small_box").height();
               var small_box_height=$(".small_box").width();
//  鼠标点距离左边界的长度与float应该与左边界的距离差半个float的width,height同理
              var mouse_left=_event.clientX-float_width_half;
              var mouse_top=_event.clientY-float_height_half;
              if(mouse_left<0){
                  mouse_left=0
              }else if (mouse_left>small_box_width-float_width){
                  mouse_left=small_box_width-float_width
              }
              if(mouse_top<0){
                  mouse_top=0
              }else if (mouse_top>small_box_height-float_height){
                  mouse_top=small_box_height-float_height
              }
               $(".float").css("left",mouse_left+"px");
               $(".float").css("top",mouse_top+"px")
               var percentX=($(".big_box img").width()-$(".big_box").width())/ (small_box_width-float_width);
               var percentY=($(".big_box img").height()-$(".big_box").height())/(small_box_height-float_height);
              console.log(percentX,percentY)
               $(".big_box img").css("left", -percentX*mouse_left+"px")
               $(".big_box img").css("top", -percentY*mouse_top+"px")
          })
    })
</script>
</body>
</html>

5. 动画效果

实例:隐藏与显示

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-2.2.3.js"></script>
    <script>
    /**
 * Created by yuan on 16/5/5.
 */
$(document).ready(function(){
    $("#hide").click(function(){
        $("p").hide(1000);
    });
    $("#show").click(function(){
        $("p").show(1000);
    });
//用于切换被选元素的 hide() 与 show() 方法。
    $("#toggle").click(function(){
        $("p").toggle();
    })
 for (var i= 0;i<7;i++){
//            颠倒了常规的$(A).append(B)的操作,即不是把B追加到A中,而是把A追加到B中。
            $("<div>").appendTo(document.body);
        }
        $("div").click(function(){
          $(this).hide(2000);
        });
});
    </script>
    <link type="text/css" rel="stylesheet" href="style.css">
</head>
<body>
    <!--1 隐藏与显示-->
    <!--2 淡入淡出-->
    <!--3 滑动-->
    <!--4 效果-回调:每一个动画执行完毕之后所能执行的函数方法或者所能做的一件事-->
    <p>hello</p>
    <button id="hide">隐藏</button>
    <button id="show">显示</button>
    <button id="toggle">隐藏/显示</button>
</body>
</html>

实例:淡入淡出

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-2.2.3.js"></script>
    <script>
    $(document).ready(function(){
   $("#in").click(function(){
       $("#id1").fadeIn(1000);
       $("#id2").fadeIn(1000);
       $("#id3").fadeIn(1000);
   });
    $("#out").click(function(){
       $("#id1").fadeOut(1000);
       $("#id2").fadeOut(1000);
       $("#id3").fadeOut(1000);
   });
    $("#toggle").click(function(){
       $("#id1").fadeToggle(1000);
       $("#id2").fadeToggle(1000);
       $("#id3").fadeToggle(1000);
   });
    $("#fadeto").click(function(){
       $("#id1").fadeTo(1000,0.4);
       $("#id2").fadeTo(1000,0.5);
       $("#id3").fadeTo(1000,0);
   });
});    
    </script>
</head>
<body>
      <button id="in">fadein</button>
      <button id="out">fadeout</button>
      <button id="toggle">fadetoggle</button>
      <button id="fadeto">fadeto</button>
      <div id="id1" style="display:none; width: 80px;height: 80px;background-color: blueviolet"></div>
      <div id="id2" style="display:none; width: 80px;height: 80px;background-color: orangered "></div>
      <div id="id3" style="display:none; width: 80px;height: 80px;background-color: darkgreen "></div>
</body>
</html>

实例:滑动

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-2.2.3.js"></script>
    <script>
    $(document).ready(function(){
     $("#flipshow").click(function(){
         $("#content").slideDown(1000);
     });
      $("#fliphide").click(function(){
         $("#content").slideUp(1000);
     });
      $("#toggle").click(function(){
         $("#content").slideToggle(1000);
     })
  });
    </script>
    <style>
        #flipshow,#content,#fliphide,#toggle{
            padding: 5px;
            text-align: center;
            background-color: blueviolet;
            border:solid 1px red;
        }
        #content{
            padding: 50px;
            display: none;
        }
    </style>
</head>
<body>
    <div id="flipshow">出现</div>
    <div id="fliphide">隐藏</div>
    <div id="toggle">toggle</div>
    <div id="content">helloworld</div>
</body>
</html>

实例:回调函数

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-2.2.3.js"></script>
    <script>
    $(document).ready(function(){
    $("button").click(function(){
       $("p").hide(1000,function(){
           alert('动画结束')
       })
//       $("p").css('color','red').slideUp(1000).slideDown(2000)
   })
});
    </script>
</head>
<body>
  <button>隐藏</button>
  <p>helloworld helloworld helloworld</p>
</body>
</html>

6. 扩展(插件机制)

  • jquery.extend({})
  • jquery.fn.extend({})

实例:商城菜单

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width">
    <meta http-equiv="X-UA-Compatible" content="IE=8">
    <title>购物商城</title>
    <style>
*{
    margin: 0;
    padding: 0;
}
.hide{
    display:none;
}
.header-nav {
    height: 39px;
    background: #c9033b;
}
.header-nav .bg{
    background: #c9033b;
}
.header-nav .nav-allgoods .menuEvent {
    display: block;
    height: 39px;
    line-height: 39px;
    text-decoration: none;
    color: #fff;
    text-align: center;
    font-weight: bold;
    font-family: 微软雅黑;
    color: #fff;
    width: 100px;
}
.header-nav .nav-allgoods .menuEvent .catName {
    height: 39px;
    line-height: 39px;
    font-size: 15px;
}
.header-nav .nav-allmenu a {
    display: inline-block;
    height: 39px;
    vertical-align: top;
    padding: 0 15px;
    text-decoration: none;
    color: #fff;
    float: left;
}
.header-menu a{
    color:#656565;
}
.header-menu .menu-catagory{
    position: absolute;
    background-color: #fff;
    border-left:1px solid #fff;
    height: 316px;
    width: 230px;
    z-index: 4;
    float: left;
}
.header-menu .menu-catagory .catagory {
    border-left:4px solid #fff;
    height: 104px;
    border-bottom: solid 1px #eaeaea;
}
.header-menu .menu-catagory .catagory:hover {
    height: 102px;
    border-left:4px solid #c9033b;
    border-bottom: solid 1px #bcbcbc;
    border-top: solid 1px #bcbcbc;
}
.header-menu .menu-content .item{
    margin-left:230px;
    position:absolute;
    background-color:white;
    height:314px;
    width:500px;
    z-index:4;
    float:left;
    border: solid 1px #bcbcbc;
    border-left:0;
    box-shadow: 1px 1px 5px #999;
}
    </style>
</head>
<body>
<div class="pg-header">
    <div class="header-nav">
        <div class="container narrow bg">
            <div class="nav-allgoods left">
                <a id="all_menu_catagory" href="#" class="menuEvent">
                    <strong class="catName">全部商品分类</strong>
                    <span class="arrow" style="display: inline-block;vertical-align: top;"></span>
                </a>
            </div>
        </div>
    </div>
    <div class="header-menu">
        <div class="container narrow hide">
            <div id="nav_all_menu" class="menu-catagory">
                <div class="catagory" float-content="one">
                    <div class="title">家电</div>
                    <div class="body">
                        <a href="#">空调</a>
                    </div>
                </div>
                <div class="catagory" float-content="two">
                    <div class="title">床上用品</div>
                    <div class="body">
                        <a href="http://www.baidu.com">床单</a>
                    </div>
                </div>
                <div class="catagory" float-content="three">
                    <div class="title">水果</div>
                    <div class="body">
                        <a href="#">橘子</a>
                    </div>
                </div>
            </div>
            <div id="nav_all_content" class="menu-content">
                <div class="item hide" float-id="one">
                    <dl>
                        <dt><a href="#" class="red">厨房用品</a></dt>
                        <dd>
                            <span>|<a href="#" target="_blank" title="勺子">勺子</a></span>
                        </dd>
                    </dl>
                    <dl>
                        <dt><a href="#" class="red">厨房用品</a></dt>
                        <dd>
                            <span>|<a href="#" target="_blank" title="菜刀">菜刀</a></span>
                        </dd>
                    </dl>
                    <dl>
                        <dt><a href="#" class="red">厨房用品</a></dt>
                        <dd>
                            <span>|<a href="#">菜板</a></span>
                        </dd>
                    </dl>
                    <dl>
                        <dt><a href="#" class="red">厨房用品</a></dt>
                        <dd>
                            <span>|<a href="#" target="_blank" title="碗"></a></span>
                        </dd>
                    </dl>
                </div>
                <div class="item hide" float-id="two">
                    <dl>
                        <dt><a href="#" class="red">厨房用品</a></dt>
                        <dd>
                            <span>|<a href="#" target="_blank" title="">角阀</a></span>
                        </dd>
                    </dl>
                    <dl>
                        <dt><a href="#" class="red">厨房用品</a></dt>
                        <dd>
                            <span>|<a href="#" target="_blank" title="角阀">角阀</a></span>
                        </dd>
                    </dl>
                    <dl>
                        <dt><a href="#" class="red">厨房用品</a></dt>
                        <dd>
                            <span>|<a href="#" target="_blank" title="角阀">角阀</a></span>
                        </dd>
                    </dl>
                </div>
                <div class="item hide" float-id="three">
                    <dl>
                        <dt><a href="#" class="red">厨房用品3</a></dt>
                        <dd>
                            <span>|<a href="#" target="_blank" title="角阀">角阀3</a></span>
                        </dd>
                    </dl>
                    <dl>
                        <dt><a href="#" class="red">厨房用品3</a></dt>
                        <dd>
                            <span>|<a href="http://www.meilele.com/category-jiaofa/" target="_blank" title="角阀">角阀3</a></span>
                        </dd>
                    </dl>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="js/jquery-2.2.3.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        Change_Menu('#all_menu_catagory','#nav_all_menu', '#nav_all_content');
    });
    function Change_Menu(all_menu_catagory,menu, content) {
        $all_menu_catagory = $(all_menu_catagory);
        $menu = $(menu);
        $content = $(content);
        $all_menu_catagory.bind("mouseover", function () {
            $menu.parent().removeClass('hide');
        });
        $all_menu_catagory.bind("mouseout", function () {
            $menu.parent().addClass('hide');
        });
        $menu.children().bind("mouseover", function () {
            $menu.parent().removeClass('hide');
            $item_content = $content.find('div[float-id="' + $(this).attr("float-content") + '"]');
            $item_content.removeClass('hide').siblings().addClass('hide');
        });
        $menu.bind("mouseout", function () {
            $content.children().addClass('hide');
            $menu.parent().addClass('hide');
        });
        $content.children().bind("mouseover", function () {
            $menu.parent().removeClass('hide');
            $(this).removeClass('hide');
        });
        $content.children().bind("mouseout", function () {
            $(this).addClass('hide');
            $menu.parent().addClass('hide');
        });
    }
</script>
</body>
</html>

实例:编辑框

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        .edit-mode{
            background-color: #b3b3b3;
            padding: 8px;
            text-decoration: none;
            color: white;
        }
        .editing{
            background-color: #f0ad4e;
        }
    </style>
</head>
<body>
    <div style="padding: 20px">
        <input type="button" onclick="CheckAll('#edit_mode', '#tb1');" value="全选" />
        <input type="button" onclick="CheckReverse('#edit_mode', '#tb1');" value="反选" />
        <input type="button" onclick="CheckCancel('#edit_mode', '#tb1');" value="取消" />
        <a id="edit_mode" class="edit-mode" href="javascript:void(0);"  onclick="EditMode(this, '#tb1');">进入编辑模式</a>
    </div>
    <table border="1">
        <thead>
        <tr>
            <th>选择</th>
            <th>主机名</th>
            <th>端口</th>
            <th>状态</th>
        </tr>
        </thead>
        <tbody id="tb1">
            <tr>
                <td><input type="checkbox" /></td>
                <td edit="true">v1</td>
                <td>v11</td>
                <td edit="true" edit-type="select" sel-val="1" global-key="STATUS">在线</td>
            </tr>
            <tr>
                <td><input type="checkbox" /></td>
                <td edit="true">v1</td>
                <td>v11</td>
                <td edit="true" edit-type="select" sel-val="2" global-key="STATUS">下线</td>
            </tr>
            <tr>
                <td><input type="checkbox" /></td>
                <td edit="true">v1</td>
                <td>v11</td>
                <td edit="true" edit-type="select" sel-val="1" global-key="STATUS">在线</td>
            </tr>
        </tbody>
    </table>
    <script type="text/javascript" src="js/jquery-2.2.3.js"></script>
    <script>
        /*
         监听是否已经按下control键
         */
        window.globalCtrlKeyPress = false;
        window.onkeydown = function(event){
            if(event && event.keyCode == 17){
                window.globalCtrlKeyPress = true;
            }
        };
        window.onkeyup = function(event){
            if(event && event.keyCode == 17){
                window.globalCtrlKeyPress = false;
            }
        };
        /*
         按下Control,联动表格中正在编辑的select
         */
        function MultiSelect(ths){
            if(window.globalCtrlKeyPress){
                var index = $(ths).parent().index();
                var value = $(ths).val();
                $(ths).parent().parent().nextAll().find("td input[type='checkbox']:checked").each(function(){                  $(this).parent().parent().children().eq(index).children().val(value);
                });
            }
        }
    </script>
    <script type="text/javascript">
$(function(){
    BindSingleCheck('#edit_mode', '#tb1');
});
function BindSingleCheck(mode, tb){
    $(tb).find(':checkbox').bind('click', function(){
        var $tr = $(this).parent().parent();
        if($(mode).hasClass('editing')){
            if($(this).prop('checked')){
                RowIntoEdit($tr);
            }else{
                RowOutEdit($tr);
            }
        }
    });
}
function CreateSelect(attrs,csses,option_dict,item_key,item_value,current_val){
    var sel= document.createElement('select');
    $.each(attrs,function(k,v){
        $(sel).attr(k,v);
    });
    $.each(csses,function(k,v){
        $(sel).css(k,v);
    });
    $.each(option_dict,function(k,v){
        var opt1=document.createElement('option');
        var sel_text = v[item_value];
        var sel_value = v[item_key];
        if(sel_value==current_val){
            $(opt1).text(sel_text).attr('value', sel_value).attr('text', sel_text).attr('selected',true).appendTo($(sel));
        }else{
            $(opt1).text(sel_text).attr('value', sel_value).attr('text', sel_text).appendTo($(sel));
        }
    });
    return sel;
}
STATUS = [
    {'id': 1, 'value': "在线"},
    {'id': 2, 'value': "下线"}
];
BUSINESS = [
    {'id': 1, 'value': "车上会"},
    {'id': 2, 'value': "二手车"}
];
function RowIntoEdit($tr){
    $tr.children().each(function(){
        if($(this).attr('edit') == "true"){
            if($(this).attr('edit-type') == "select"){
                var select_val = $(this).attr('sel-val');
                var global_key = $(this).attr('global-key');
                var selelct_tag = CreateSelect({"onchange": "MultiSelect(this);"}, {}, window[global_key], 'id', 'value', select_val);
                $(this).html(selelct_tag);
            }else{
                var orgin_value = $(this).text();
                var temp = "<input value='"+ orgin_value+"' />";
                $(this).html(temp);
            }
        }
    });
}
function RowOutEdit($tr){
    $tr.children().each(function(){
        if($(this).attr('edit') == "true"){
            if($(this).attr('edit-type') == "select"){
                var new_val = $(this).children(':first').val();
                var new_text = $(this).children(':first').find("option[value='"+new_val+"']").text();
                $(this).attr('sel-val', new_val);
                $(this).text(new_text);
            }else{
                var orgin_value = $(this).children().first().val();
                $(this).text(orgin_value);
            }
        }
    });
}
function CheckAll(mode, tb){
    if($(mode).hasClass('editing')){
        $(tb).children().each(function(){
            var tr = $(this);
            var check_box = tr.children().first().find(':checkbox');
            if(check_box.prop('checked')){
            }else{
                check_box.prop('checked',true);
                RowIntoEdit(tr);
            }
        });
    }else{
        $(tb).find(':checkbox').prop('checked', true);
    }
}
function CheckReverse(mode, tb){
    if($(mode).hasClass('editing')){
        $(tb).children().each(function(){
            var tr = $(this);
            var check_box = tr.children().first().find(':checkbox');
            if(check_box.prop('checked')){
                check_box.prop('checked',false);
                RowOutEdit(tr);
            }else{
                check_box.prop('checked',true);
                RowIntoEdit(tr);
            }
        });
    }else{
        //
        $(tb).children().each(function(){
            var tr = $(this);
            var check_box = tr.children().first().find(':checkbox');
            if(check_box.prop('checked')){
                check_box.prop('checked',false);
            }else{
                check_box.prop('checked',true);
            }
        });
    }
}
function CheckCancel(mode, tb){
    if($(mode).hasClass('editing')){
        $(tb).children().each(function(){
            var tr = $(this);
            var check_box = tr.children().first().find(':checkbox');
            if(check_box.prop('checked')){
                check_box.prop('checked',false);
                RowOutEdit(tr);
            }else{
            }
        });
    }else{
        $(tb).find(':checkbox').prop('checked', false);
    }
}
function EditMode(ths, tb){
    if($(ths).hasClass('editing')){
        $(ths).removeClass('editing');
        $(tb).children().each(function(){
            var tr = $(this);
            var check_box = tr.children().first().find(':checkbox');
            if(check_box.prop('checked')){
                RowOutEdit(tr);
            }else{
            }
        });
    }else{
        $(ths).addClass('editing');
        $(tb).children().each(function(){
            var tr = $(this);
            var check_box = tr.children().first().find(':checkbox');
            if(check_box.prop('checked')){
                RowIntoEdit(tr);
            }else{
            }
        });
    }
}
    </script>
</body>
</html>

四、文件上传三种方式

1. Form表单上传文件

############### views ##################
import os
def upload(request):
    if request.method == 'GET':
        img_list = models.Img.objects.all()
        return render(request,'upload.html',{'img_list': img_list})
    elif request.method == "POST":
        user = request.POST.get('user')
        fafafa = request.POST.get('fafafa')
        obj = request.FILES.get('fafafa')

        file_path = os.path.join('static','upload',obj.name)
        f = open(file_path, 'wb')
        for chunk in obj.chunks():
            f.write(chunk)
        f.close()

        models.Img.objects.create(path=file_path)

        return redirect('/upload.html')
############### upload.html ################
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{#    enctype="multipart/form-data" 代表要上传文件#}
    <form method="POST" action="/upload.html" enctype="multipart/form-data">
        <input type="text" name="user" />
        <input type="file" name="fafafa" />
        <input type="submit" value="提交" />
    </form>

    <div>
        {% for item in img_list %}
            <img style="height: 200px;width: 200px;" src="/{{ item.path }}" />
        {% endfor %}
    </div>
</body>
</html>

2. 基于FormData实现文件上传(XMLHttpRequest和jQuery)

############# views ##############
import os
def upload(request):
    if request.method == 'GET':
        img_list = models.Img.objects.all()
        return render(request, 'upload_xml.html', {'img_list': img_list})
    elif request.method == "POST":
        user = request.POST.get('user')
        fafafa = request.POST.get('fafafa')
        obj = request.FILES.get('fafafa')

        file_path = os.path.join('static','upload',obj.name)
        f = open(file_path, 'wb')
        for chunk in obj.chunks():
            f.write(chunk)
        f.close()

        models.Img.objects.create(path=file_path)
        ret = {'status':True,'path':file_path}
        return HttpResponse(json.dumps(ret))
############### upload_xml.html ################
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .container img{
            width: 200px;
            height: 200px;
        }
    </style>
</head>
<body>
    <div class="container" id="imgs">
        {% for img in img_list %}
            <img src="/{{ img.path }}">
        {% endfor %}
    </div>

    <input type="file" id="img" />
    <input type="submit" value="提交xml" onclick="UploadXML()" />
    <input type="submit" value="提交jq" onclick="Uploadjq()" />
    <script src="/static/jquery-2.1.4.min.js"></script>
    <script>
        {#用XMLHttpRequest实现:#}
        function UploadXML() {
            var dic = new FormData();
            dic.append('user','v1');
            {#获取当前上传的文件对象:#}
            dic.append('fafafa',document.getElementById('img').files[0]);

            var xml = new XMLHttpRequest();
            xml.open('post', '/upload_xml.html', true);
            xml.onreadystatechange = function () {
                if(xml.readyState == 4){
                    var obj = JSON.parse(xml.responseText);
                    if(obj.status){
                        var img = document.createElement('img');
                        img.src = "/" + obj.path;
                        document.getElementById("imgs").appendChild(img);
                    }
                }
            };
            xml.send(dic);
        }

        {#用jquery实现:#}
        function Uploadjq() {
            var dic = new FormData();
            dic.append('user','v1');
            {#获取当前上传的文件对象:#}
            dic.append('fafafa',document.getElementById('img').files[0]);

            $.ajax({
                url: '/upload_xml.html',
                type: 'POST',
                data: dic,
                processData: false,  // 告诉jQuery不要处理这个数据
                contentType: false,  // 告诉jQuery不要设置这个contentType
                dataType: 'JSON',
                success: function(arg){
                    var img = document.createElement('img');
                    img.src = "/" + arg.path;
                    $('#imgs').append(img);
                }
            })
        }
    </script>
</body>
</html>

3. 基于iframe和form表单伪造ajax并实现文件上传

由于低版本的浏览器不支持FormData,而前两种文件上传均依赖FormData,考虑到代码的兼容性,该方式是三种里兼容性最好的。

############## views #################
import os
def upload(request):
    if request.method == 'GET':
        img_list = models.Img.objects.all()
        return render(request, 'upload_iframe.html', {'img_list': img_list})
    elif request.method == "POST":
        user = request.POST.get('user')
        fafafa = request.POST.get('fafafa')
        obj = request.FILES.get('fafafa')

        file_path = os.path.join('static','upload',obj.name)
        f = open(file_path, 'wb')
        for chunk in obj.chunks():
            f.write(chunk)
        f.close()

        models.Img.objects.create(path=file_path)
        ret = {'status':True,'path':file_path}
        return HttpResponse(json.dumps(ret))
############## upload_iframe.html ###############
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .container img{
            width: 200px;
            height: 200px;
        }
    </style>
</head>
<body>
    <div class="container" id="imgs">
        {% for img in img_list %}
            <img src="/{{ img.path }}">
        {% endfor %}
    </div>

    <input type="file" id="img" />
    <input type="text" id="url" />
    <input type="button" value="点我" onclick="iframeChange();" />
    <iframe id="ifr" src=""></iframe>
    <hr/>

    <form method="POST" action="/upload_iframe.html" target="iframe_1" enctype="multipart/form-data">
        <iframe style="display: none" id="iframe_1" name="iframe_1" src="" onload="loadIframe();"></iframe>
        <input type="text" name="user" />
        <input type="file" name="fafafa" />
        <input type="submit" value="提交" />
    </form>

    <script src="/static/jquery-2.1.4.min.js"></script>
    <script>
        function iframeChange() {
            var url = $('#url').val();
            $('#ifr').attr('src',url);
        }

        function loadIframe(){
            // 获取iframe内部的内容:
            var str_json = $('#iframe_1').contents().find('body').text();
            var obj = JSON.parse(str_json);
            if(obj.status){
                var img = document.createElement('img');
                img.src = "/" + obj.path;
                $('#imgs').append(img);
            }
        }
    </script>
</body>
</html>

==================================================================
参考文献:
https://www.cnblogs.com/yuanchenqi/articles/5663118.html

本篇涉及代码见week13 —> day49, day50

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值