懂這點js基本就夠擼很久web了

<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'
})
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,993評論 19 139
  • 通過jQuery,您可以選取(查詢,query)HTML元素,并對它們執行“操作”(actions)。 jQuer...
    枇杷樹8824閱讀 671評論 0 3
  • 去年國慶,我和朋友淺淺一起去登泰山,在山腰上偶遇他的大學同學,一個眉清目秀的大小伙,背著藍色的雙肩背包,拄著一根登...
    果苒閱讀 515評論 2 6
  • 一直認為,孩子的成長不僅僅只在學校讀書這件事,而出去旅行,增長見識更加重要,也是學習!暑假因為補課,時間不湊...
    日光傾城52fhx閱讀 395評論 0 0
  • 2017年7月18日 星期二 晴 要說亮點行程,今天的每一站都是亮點,相信今天也是本次日本游學夏令營中有...
    Q錢多多閱讀 927評論 0 1