• jsweb常用代码


    <script>
        $(function (){
            $.ajax({
                url: 'https://test.com:8080/api/v1/users?query_not_auth=100&start=0&num=10',
                dataType: 'jsonp',
                headers:{
                    'x-user':'1111',
                    'Authorization':'Bearer '+'111111'
                },
                success:function(data){
                    if (data != null && data.users != null) {
                        for (var i = 0; i < data.users.length; i++) {
                            $('.search_bar_wrap').after(generateDom(data.users[i]));
                        }
                    }
                }
            });
    
            $(document).on('click','.outer.primary', function (){
    
                $.weui.confirm('确认审核通过?',{title:'头像审核'}, function (){
    
                }, function (){
    
                });
            });
            $(document).on('click','.outer.default', function (){
                $.weui.confirm('确认不合格?',{title:'头像审核'}, function (){
    
                }, function (){
    
                });
            });
            $('.search_bar_wrap').searchBar({
                //替换原模板的“取消”
                cancelText:"取消",
                //替换原模板的“搜索”
                searchText:'可搜索昵称、QQ号码、学校',
                //搜索栏获得焦点时
                onfocus: function (value) {
                    console.log('focus!The value is '+value);
                },
                //搜索栏失去焦点时
                onblur:function(value) {
                    console.log('blur!The value is '+value);
                },
                //搜索栏在输入时
                oninput: function(value) {
                    console.log('Input!The value is '+ value);
                },
                //搜索栏提交时,如果没有submit方法,则沿用浏览器默认的提交方式
                onsubmit:function(value){
                    console.log('Submit!The value is '+ value);
                },
                //点击取消按钮
                oncancel:function(){
                    console.log('click cancel');
                },
                //点击清空按钮
                onclear:function(){
                    console.log('click clear');
                }
            });
        })
    
    function generateDom(user){
    
        var type1 = `
        <div class="weui_panel weui_panel_access panel">
            <div class="weui_panel_hd apply-id">$time $name <span>申请</span><span>$gender</span></div>
            <div class="weui_panel_bd">
                <div class="weui_media_box weui_media_text">
                    [站外图片上传中……(1)]
                </div>
            </div>
            <div class="weui_dialog_ft panel-btn">
                <a href="javascript:;" class="weui_btn_dialog outer primary">审核通过</a>
                <a href="javascript:;" class="weui_btn_dialog outer default">不合格</a>
            </div>
        </div>`;
    
        var type2 = `
        <div class="weui_panel weui_panel_access panel">
            <div class="weui_panel_hd apply-id">$time $name <span>申请</span><span>$gender</span></div>
            <div class="weui_panel_bd">
                <div class="weui_media_box weui_media_text">
                    [站外图片上传中……(2)]
                </div>
            </div>
            <div class="weui_panel_hd panel-bottom">$state</div>
        </div>`;
    
        var result = '';
        switch(user.jobauth){
            case 0:
            case 100:
            result = type1.replace('$time',timestamp2date(user.updatetime)).replace('$name',user.name).replace('$gender',user.gender==1?'男':'女').replace('$pic',user.head);
            break;
            case 400:
            case -400:
            result = type2.replace('$time',timestamp2date(user.updatetime)).replace('$name',user.name).replace('$gender',user.gender==1?'男':'女').replace('$pic',user.head).replace('$state',user.jobauth==400?"已审核通过":"已拒绝");
            break;
        }
    
        return result;
    }
    function timestamp2date(timestamp){
        var date = new Date();
        date.setTime(timestamp);
        M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
        D = date.getDate() + ' ';
        h = date.getHours() + ':';
        m = date.getMinutes() + ' ';
        return M+D+h+m;
    }
    
    </script>

    很久不撸js了,发现自己已撸,依然连代码都不会写了,好在之前的思维都在。

    js操作用得最多的,无非有以下几点:

    • 1、操作dom节点,包括,查找,动态添加dom
    • 2、ajax发送网络请求,要知道跨域如何处理。
    • 3、不能在多了,就以上两点了。

    对于操作dom节点来说,其最主要的是要去定位你要找的dom节点!
    然而我们已经回不到那个findElementById的那个时代了。
    就jquery来说吧,移动端zepto其实也是一样。
    # 对应于id.对应于class相信懂的人一看就会,但是其他的,你不经常写,未必就记得,不记得怎么办,参考这里:
    http://www.w3school.com.cn/jquery/jquery_ref_selectors.asp 。
    如果你很懒,那么我也不得不贴一些要点出来:

    • jQuery 元素选择器 | jQuery 使用 CSS 选择器来选取 HTML 元素。
      $("p") 选取 <p> 元素。
      $("p.intro") 选取所有 class="intro" 的 <p> 元素。
      $("p#demo") 选取所有 id="demo" 的 <p> 元素。
    • jQuery 属性选择器 | jQuery 使用 XPath 表达式来选择带有给定属性的元素。
      $("[href]") 选取所有带有 href 属性的元素。
      $("[href='#']") 选取所有带有 href 值等于 "#" 的元素。
      $("[href!='#']") 选取所有带有 href 值不等于 "#" 的元素。
      $("[href$='.jpg']") 选取所有 href 值以 ".jpg" 结尾的元素。
    • 更多的选择器实例
      $(this)    当前 HTML 元素
      $("p")    所有 <p> 元素
      $("p.intro")    所有 class="intro" 的 <p> 元素
      $(".intro")    所有 class="intro" 的元素
      $("#intro")    id="intro" 的元素
      $("ul li:first")    每个 <ul> 的第一个 <li> 元素
      $("[href$='.jpg']")    所有带有以 ".jpg" 结尾的属性值的 href 属性
      $("div#intro .head")    id="intro" 的 <div> 元素中的所有 class="head" 的元素
      $("a,li,p") 所有的,a,li,p元素。

    其次想回顾下的主要有两个方面,事件,以及操作文档。
    对于事件,也不想作太多的回顾,用得最多的无非就是click,但是有一点需要注意,动态添加的文本,也想有click事件怎么办?

    以下两种,均不会对后续动态增加进来的元素产

    on(type, [selector], function(e){ ... })  ⇒ self
    on(type, [selector], [data], function(e){ ... })  ⇒ self 
    on({ type: handler, type2: handler2, ... }, [selector])  ⇒ self
    on({ type: handler, type2: handler2, ... }, [selector], [data])  ⇒ self
    var elem = $('.content')
    // observe all clicks inside dom of  class named content:
    elem.on('click', function(e){ ... })
    // observe clicks inside navigation links in .content
    elem.on('click', 'nav a', function(e){ ... })

    而以下两种均会对后续动态添加进来的a,节点,nav 下的 a节点其作用。

    // all clicks inside links in the document
    $(document).on('click', 'a', function(e){ ... })
    // disable following any navigation link on the page
    $(document).on('click', 'nav a', false)

    最后,想回顾的自然是网络相关的操作,当然,本人也很懒,只想回顾下ajax罢了:

    • type
      (default: “GET”): HTTP request method (“GET”, “POST”, or other)
    • url
      (default: current URL): URL to which the request is made
    • data
      (default: none): data for the request; for GET requests it is appended to query string of the URL. Non-string objects will get serialized with $.param
    • processData
      (default: true): whether to automatically serialize data
      for non-GET requests to string
    • contentType
      (default: “application/x-www-form-urlencoded”): the Content-Type of the data being posted to the server (this can also be set via headers
      ). Pass false
      to skip setting the default value.
    • mimeType
      (default: none): override the MIME type of the response. v1.1+
    • dataType
      (default: none): response type to expect from the server. One of json
      , jsonp
      , script
      , xml
      ,html
      , or text
      .
    • jsonp
      (default: “callback”): the name of the JSONP callback query parameter
    • jsonpCallback
      (default: “jsonp{N}”): the string (or a function that returns) name of the global JSONP callback function. Set this to enable browser caching. v1.1+
    • timeout
      (default: 0
      ): request timeout in milliseconds, 0
      for no timeout
    • headers
      : object of additional HTTP headers for the Ajax request
    • async
      (default: true): set to false
      to issue a synchronous (blocking) request
    • global
      (default: true): trigger global Ajax events on this request
    • context
      (default: window): context to execute callbacks in
    • traditional
      (default: false): activate traditional (shallow) serialization of data
      parameters with $.param
    • cache
      (default: true): whether the browser should be allowed to cache GET responses. Since v1.1.4, the default is false
      for dataType: "script"
      or jsonp
      .
    • xhrFields
      (default: none): an object containing properties to be copied over verbatim to the XMLHttpRequest instance. v1.1+
    • username & password
      (default: none): HTTP Basic authentication credentials. v1.1+
    $(document).on('ajaxBeforeSend', function(e, xhr, options){ 
    // This gets fired for every Ajax request performed on the page. 
    // The xhr object and $.ajax() options are available for editing. 
    // Return false to cancel this request.
    })
    
    $.ajax({ 
    type: 'GET', url: '/projects', 
    // data to be added to query string: 
    data: { name: 'Zepto.js' }, 
    // type of data we are expecting in return: 
    dataType: 'json',
     timeout: 300, 
    context: $('body'), 
    success: function(data){ 
    // Supposing this JSON payload was received: 
    // {"project": {"id": 42, "html": "<div>..." }} 
    // append the HTML to context object. 
    this.append(data.project.html) 
    }, 
    error: function(xhr, type){ alert('Ajax error!') }
    })
    
    // post a JSON payload:
    $.ajax({ 
    type: 'POST', 
    url: '/projects', 
    // post payload: 
    data: JSON.stringify({ name: 'Zepto.js' }), 
    contentType: 'application/json'
    })
  • 相关阅读:
    【安卓本卓】Android系统源码篇之(一)源码获取、源码目录结构及源码阅读工具简介
    【朝花夕拾】Android性能篇之(六)Android进程管理机制
    【烂笔头】adb命令篇
    【朝花夕拾】Android性能篇之(五)Android虚拟机
    【朝花夕拾】Android性能篇之(一)序言及JVM
    【烂笔头】git常用命令篇
    【朝花夕拾】Android性能篇之(四)Apk打包
    【朝花夕拾】Android Log篇
    从2015年百度站长的一则公告回头看百度的骚操作
    ASP.NET Core+Quartz.Net 实现web定时任务
  • 原文地址:https://www.cnblogs.com/clphp/p/6392722.html
Copyright © 2020-2023  润新知