分类 JQ 下的文章

jq -項目記錄,雜亂

判定 ie8

(function(){
    var BrowserDetect = {
        init: function () {
            this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
            this.version = this.searchVersion(navigator.userAgent)
            || this.searchVersion(navigator.appVersion)
            || "an unknown version";
            this.OS = this.searchString(this.dataOS) || "an unknown OS";
        },
        searchString: function (data) {
            for (var i=0;i<data.length;i++)    {
                var dataString = data[i].string;
                var dataProp = data[i].prop;
                this.versionSearchString = data[i].versionSearch || data[i].identity;
                if (dataString) {
                    if (dataString.indexOf(data[i].subString) != -1)
                        return data[i].identity;
                }
                else if (dataProp)
                    return data[i].identity;
            }
        },
        searchVersion: function (dataString) {
            var index = dataString.indexOf(this.versionSearchString);
            if (index == -1) return;
            return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
        },
        dataBrowser: [
            {
                string: navigator.userAgent,
                subString: "Chrome",
                identity: "Chrome"
            },
            {     string: navigator.userAgent,
                subString: "OmniWeb",
                versionSearch: "OmniWeb/",
                identity: "OmniWeb"
            },
            {
                string: navigator.vendor,
                subString: "Apple",
                identity: "Safari",
                versionSearch: "Version"
            },
            {
                prop: window.opera,
                identity: "Opera"
            },
            {
                string: navigator.vendor,
                subString: "iCab",
                identity: "iCab"
            },
            {
                string: navigator.vendor,
                subString: "KDE",
                identity: "Konqueror"
            },
            {
                string: navigator.userAgent,
                subString: "Firefox",
                identity: "Firefox"
            },
            {
                string: navigator.vendor,
                subString: "Camino",
                identity: "Camino"
            },
            {        // for newer Netscapes (6+)
                string: navigator.userAgent,
                subString: "Netscape",
                identity: "Netscape"
            },
            {
                string: navigator.userAgent,
                subString: "MSIE",
                identity: "Internet Explorer",
                versionSearch: "MSIE"
            },
            {
                string: navigator.userAgent,
                subString: "Gecko",
                identity: "Mozilla",
                versionSearch: "rv"
            },
            {         // for older Netscapes (4-)
                string: navigator.userAgent,
                subString: "Mozilla",
                identity: "Netscape",
                versionSearch: "Mozilla"
            }
        ],
        dataOS : [
            {
                string: navigator.platform,
                subString: "Win",
                identity: "Windows"
            },
            {
                string: navigator.platform,
                subString: "Mac",
                identity: "Mac"
            },
            {
                string: navigator.userAgent,
                subString: "iPhone",
                identity: "iPhone/iPod"
            },
            {
                string: navigator.platform,
                subString: "Linux",
                identity: "Linux"
            }
        ]

    };
    BrowserDetect.init();
    if(BrowserDetect.version <= 8 && BrowserDetect.browser.indexOf('Explorer') != -1 ){
        var browsehappy = document.createElement('div')
        browsehappy.className = 'browsehappy'
        browsehappy.innerHTML = 'You are using an outdated browser. Please <a href="http://browsehappy.com/" target="_blank">upgrade your browser</a> to improve your experience.'
        document.body.id = 'ie8'
        document.body.appendChild(browsehappy)
    }
})();

全屏輪播圖,方法一,其實並非優級,需引入 jquery.transit.js,圖片規格為四級:pc:1920 xx ;m:640 xx; ipad: 1366 1024 ; 1024 1366

function Eononslide(o) {
    if(!o.length){return}
    this.o = $(o);
    this.hd = this.o.find('.hd');
    this.hdul = this.hd.find('ul');
    this.hdli = this.hdul.find('li');
    this.bd = this.o.find('.bd');
    this.bdul = this.bd.find('ul');
    this.bdli = this.bdul.find('li');
    this.lastli = this.bdli.last().clone(true)
    this.firstli = this.bdli.first().clone(true)
    this.imgsrc = this.bdli.find('.bdimg').eq(0).attr('src');
    this.pn = this.o.find('.pn');
    this.pna = this.pn.find('a');
    this.lilen = this.bdli.length;
    this.num = 1;
    this.b = !0;
    this._t = null;
    this._t_m = null;
    this.downX = 0;
    this.dTime = 0;
    this.bdul.prepend(this.lastli).append(this.firstli);
    this.or = 4;//>766
    this.m = 1;
    this.etc = ''
    var at = ''
    this.options = {
        'autoPlay': true,
        'pn': false,
        'touch': true,
        'hd': true,
        'speed':300,
        'easing':'swing',
        callback:function(){}
    }
}
Eononslide.prototype = {
    constructor: Eononslide,
    init: function (opt) {
        $.extend(this.options, opt);
        this._cssUse()
        this._imgLoad();
        this.options.autoPlay && this._hd();
        this.options.autoPlay && this._autoPlay();
        this.options.touch && this._touchmove();
        this._resize();
        this._landport();
    },
    _changeW: function () {
        if (this.or == 0) {
            return $(window).width()
        }
        else if (this.or == 1) {
            return 768
        }
        else if (this.or == 2){
            return 1024
        }
        else if(this.or == 3){
            return 1366
        }
        else(this.or == 4)
        {
           // return 1920  //中心點縮進
            return $(window).width()
        }
    },
    _imgLoad: function () {
        var _this = this;
        var imgload = new Image();
        imgload.src = _this.imgsrc;
        _this._imgresizeW()
        imgload.onload = function () {
            typeof _this.options.callback == 'function' && _this.options.callback();
            setTimeout(function(){
                var _liallimg = _this.bdul.find('.bdimg')
                _liallimg.css('opacity',1)
                _this.options.pn && _this._pnRun();
            },300)
        }
    },
    _or: function () {
        if ($(window).width() < 766) {
            this.or = 0;  // <766
        }
        else if ($(window).width() == 768) {
            this.or = 1; // 766
        }
        else if($(window).width() == 1024){
            this.or = 2;
        }
        else if($(window).width() == 1366){
            this.or = 3;
        }
        else {
            this.or = 4;//>766
        }
        return this.or;
    },
    _imgresizeW: function () {
        var _this = this;
        _this._or()
        var _initL = $(window).width() - _this._changeW() < 0 ? $(window).width() - _this._changeW() : 0
        var _liali = _this.bdul.find('li')
        var j = {}
        var j2 = {}
        var j3 = {}
        j[at] = _initL / 2 + 'px'
        j["width"] = _this._changeW() + 'px'
        j2[at] = 'auto'
        j2["width"] = _this._changeW()
        j2['height'] = _this._changeW() * 1.32
        j3[at] = -_this._changeW()
        j3["width"] = (_this.lilen + 2) * _this._changeW()
        function _pl() {
            if ($(window).width() == 1024 && (window.orientation == 90 || window.orientation == -90)) {   //横
                if (_this.or == 2) {
                    _this.o.css({'height': '768px', 'max-height': '768px'})
                }
            }
            if ($(window).width() == 1024 && (window.orientation == 180 || window.orientation == 0)) {  //竖
                if (_this.or == 2) {
                    _this.o.css({'height': '1366px', 'max-height': '1366px'})
                }
            }
            if ($(window).width() == 1366 && (window.orientation == 90 || window.orientation == -90)) {  //横
                if (_this.or == 2) {
                    _this.o.css({'height': '1366px', 'max-height': '1366px'})
                }
            }
        }
            window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", _pl, false);
        if (_this.or == 0) {
            _liali.css(j2);
            _this.o.css({'height': Math.ceil(_this._changeW() * 1.33)})
        }
        if (_this.or == 1 || _this.or == 2 || _this.or == 3 || _this.or == 4) {
            _liali.css(j)
        }
        if (_this.or == 1) {
            _this.o.css({'height': '925px', 'max-height': '925px'})
        }

        if ($(window).width() == 768) {
            if (_this.or == 2) {
                _this.o.css({'height': '1024px', 'max-height': '1024px'})
            }
        }
        if ($(window).width() == 1024 && (window.orientation == 90 || window.orientation == -90)) { //横
            if (_this.or == 2) {
                _this.o.css({'height': '768px', 'max-height': '768px'})
            }
        }
        if ($(window).width() == 1024 && (window.orientation == 180 || window.orientation == 0)) {  //竖
            if (_this.or == 2) {
                _this.o.css({'height': '1366px', 'max-height': '1366px'})
            }
        }
        _pl()
        if(_this.or == 3 ){
            _this.o.css({'height': '1024px','max-height':'1024px'})
        }
        if (_this.or == 4) {
            _this.o.css({'height': Math.ceil(_this._changeW() / 2.33)})
        }
        _this.bdul.css(j3)
    },
    _hd: function () {
        var html = ''
        var _this = this;
        for (var i = 0; i < this.lilen; i++) {
            html += '<li></li>'
        }
        this.hdul.html(html)
        this.hdli = this.hdul.find('li')
        if (this.lilen > 0) {
            this.hdli.first().addClass('on')
        }
        this.hdli.on('click', function (e) {
            e.stopPropagation()
            $(this).addClass('on').siblings().removeClass('on')
            _this._hdRun($(this).index());
        })
        return this;
    },
    _hdRun: function (_index) {
        var _this = this;
        var j = {}
        j[at] = -(_index + 1) * this._changeW()
        this.bdul.stop(true, true)[_this.etc](j, function () {
            _this.num = _index + 1;
        })
    },
    _hdon: function () {
        this.hdli = this.hdul.find('li')
        var _linum = this.num - 1;
        if (_linum == this.lilen) {
            _linum = 0;
        }
        this.hdli.eq(_linum).addClass('on').siblings().removeClass('on')
    },
    _pnRun: function () {
        var _this = this;
        this.pna.eq(1).on('click', function (e) {
            e.stopPropagation()
            _this._Rrun()
        })
        this.pna.eq(0).on('click', function (e) {
            e.stopPropagation()
            _this._Lrun()
        })
        this.o.on({
            'mouseenter': function () {
                _this.pn.show('fast')
            },
            'mouseleave': function () {
                _this.pn.hide('fast')
            }
        })
        _this.pn.css({'opacity':1})
        return this;
    },
    _Rrun: function () {
        var _this = this;
        if (this.b) {
            this.num++;
            this.b = !1
            var j = {}
            var j2 = {}
            j[at] = -_this._changeW() * this.num;
            j2[at] = - _this._changeW();
            this.bdul[_this.etc](j, _this.options.speed,_this.options.easing, function () {
                if (_this.num == _this.lilen + 1) {
                    _this.bdul.css(j2)
                    _this.num = 1
                }
                _this.b = !0;
                _this.m = 1;
            })
            _this._hdon()
        }
    },
    _Lrun: function () {
        var _this = this;
        if (this.b) {
            this.num--;
            this.b = !1;
            var j = {}
            var j2 = {}
            j[at] = - this._changeW() * this.num;
            j2[at] = -_this._changeW() * _this.lilen
            this.bdul.stop(true)[_this.etc](j, _this.options.speed,_this.options.easing, function () {
                if (_this.num == 0) {
                    _this.bdul.css(j2)
                    _this.num = _this.lilen;
                }
                _this.b = !0;
                _this.m = 1;
            })
            _this._hdon()
        }
    },
    _autoPlay: function () {
        var _this = this;
        this._t = setInterval(function () {
            _this._Rrun()
        }, 8000)
        clautoPlay(_this.bdul);
        clautoPlay(_this.hd);
        clautoPlay(_this.pn);
        function clautoPlay(obj) {
            obj.on({
                'mouseenter': function () {
                    clearInterval(_this._t)
                    _this._t = null;
                },
                'mouseleave': function () {
                    clearInterval(_this._t)
                    _this._t = setInterval(function () {
                        _this._Rrun()
                    }, 8000)
                }
            })
        }
    },
    _touchmove: function () {
        var _this = this;
        var xx,yy,XX,YY,swipeX,swipeY;
        _this.bdul.on('touchstart', function (e) {
            xx = e.originalEvent.changedTouches[0].pageX;
            yy = e.originalEvent.changedTouches[0].pageY;
            swipeX = true;
            swipeY = true;
            clearInterval(_this._t);
            var touch = e.originalEvent.changedTouches[0];
            _this.downX = touch.pageX;
            if (_this.m) {
                var initLeft = parseInt(_this.bdul.css(at))
                _this.m = 0;
            }
            _this.dTime = Date.now();
            _this.bdul.on('touchmove', function (e) {
                XX = e.originalEvent.changedTouches[0].pageX;
                YY = e.originalEvent.changedTouches[0].pageY;
                var touch = e.originalEvent.changedTouches[0];
                var disX = touch.pageX - _this.downX;
                var j = {}
                var j2 = {}
                j[at] = initLeft + disX
                j2[at] = initLeft
                if (swipeX && Math.abs(XX - xx) - Math.abs(YY - yy) > 0) {
                    e.stopPropagation();
                    e.preventDefault();
                    swipeY = false ;
                    if (Math.abs(disX) > 20) {
                        _this.bdul.css(j)
                    }
                    else {
                        _this.bdul.css(j2)
                    }
                }
                else if (swipeY && Math.abs(XX - xx) - Math.abs(YY - yy) < 0) {
                    swipeX = false;
                }

            });
            _this.bdul.on('touchend', function (e) {
                XX = e.originalEvent.changedTouches[0].pageX;
                YY = e.originalEvent.changedTouches[0].pageY;
                _this._cssUse()
                var touch = e.originalEvent.changedTouches[0];
                var j = {}
                j[at] = initLeft
                if (swipeX && Math.abs(XX - xx) - Math.abs(YY - yy) > 0) {
                    e.stopPropagation();
                    e.preventDefault();
                    swipeY = false ;
                if (touch.pageX < _this.downX) {
                    if (Date.now() - _this.dTime < 200 && Date.now() - _this.dTime > 30) {
                        _this._Rrun();
                    }
                    else {
                        _this.bdul[_this.etc](j, _this.options.speed,_this.options.easing, function () {
                            _this.m = 1;
                        })
                    }
                }
                else {
                    if (Date.now() - _this.dTime < 200 && Date.now() - _this.dTime > 30) {
                        _this._Lrun();
                    }
                    else {
                        _this.bdul[_this.etc](j,  _this.options.speed,_this.options.easing, function () {
                            _this.m = 1;
                        })
                    }
                }
                _this.bdul.off('touchmove');
                _this.bdul.off('touchend');
                }
                else if (swipeY && Math.abs(XX - xx) - Math.abs(YY - yy) < 0) {
                    swipeX = false;
                }
            })
        })
    },
    _resize: function () {
        var _this = this;
        $(window).resize(function () {
            _this._imgresizeW()
        })
    },
    _landport:function(){
        var _this = this;
        var _mq = window.matchMedia("(orientation: portrait)");
        _mq.addListener(function (m) {
            if (m.matches) {
                _this._imgresizeW()
            }
            else {
                _this._imgresizeW()
            }

        });
    },
    _cssUse:function(){
        if(!!$.support.transition){
            this.etc = 'transition'
            at = 'x'
            this.options.speed = '300'
            this.options.easing = 'linear'
        }
        else{
            this.etc = 'animate'
            at = 'left'
        }
    }
}
<div class="i-banner">
<div class="i-banner-slide">
    <div class="hd">
        <ul></ul>
    </div>
    <div class="bd">
        <ul><li><img class='bdimg' src='1.png' /><a href='#' class='i-banner-bda-1'></a></li></ul>
        <ul><li><img class='bdimg' src='2.png' /></li></ul>
        <ul><li><img class='bdimg' src='3.png' /></li></ul>
    </div>
    <div class="pn">
        <a href="javascript:;"></a>
        <a href="javascript:;"></a>
    </div>
</div>
</div>
.i-banner-slide{position:relative;min-height:300px}
.i-banner-slide .bd ul{position:absolute;left:0;margin:0;padding:0;}
.i-banner-slide .bd li{list-style:none;float:left;margin:0;padding:0;background:url(/img/loading.gif) center center no-repeat}
.i-banner-slide .bd .bdimg{position:relative;left:0;width:100%;vertical-align:top;filter:alpha(opacity=0);-moz-opacity:0;opacity:0;-webki-transition:opacity .3s;-moz-transition:opacity .3s;-ms-transition:opacity .3s;-o-transition:opacity .3s;transition:opacity .3s;min-width:320px}
.i-banner-slide .hd{position:absolute;width:100%;text-align:center;bottom:20px;z-index:1}
.i-banner-slide .hd li{cursor:pointer;display:inline-block;width:10px;height:10px;border-radius:50%;margin:0 9px;background-color:#646464;border:1px solid #646464}
.i-banner-slide .hd .on{border:1px solid #fff;background-color:transparent}
.i-banner-slide .pn{font-size:28px;opacity:0;-webkit-transition:.5s;-moz-transition:.5s;-ms-transition:.5s;transition:.5s;}
.i-banner-slide .pn a{display:inline-block;text-decoration:none;position:absolute;top:50%;margin:-57px auto auto;outline:0;width:55px;height:114px;border:none;overflow:hidden;background:no-repeat transparent;cursor:pointer;color:#FFF;line-height:114px}
.cart_empty a:hover,.footer a:hover{text-decoration:underline}
.h-nav-cart-c{display:none;position:relative}
.i-banner-slide .pn a:nth-of-type(1):after,.i-banner-slide .pn a:nth-of-type(2):after{content:'';border-bottom:1px solid #797979;width:50px;height:50px;top:50%;margin-top:-25px;position:absolute}
.i-banner-slide .pn a:nth-of-type(1){left:0}
.i-banner-slide .pn a:nth-of-type(1):after{border-left:1px solid #797979;-webkit-transform:rotate(45deg);-moz-transform:rotate(45deg);-ms-transform:rotate(45deg);transform:rotate(45deg);left:18px}
.i-banner-slide .pn a:nth-of-type(2){right:0}
.i-banner-slide .pn a:nth-of-type(2):after{border-right:1px solid #797979;-webkit-transform:rotate(-45deg);-moz-transform:rotate(-45deg);-ms-transform:rotate(-45deg);transform:rotate(-45deg);right:18px}
.i-banner-slide .pn a:hover{outline:0}
.i-banner-slide .bd li{position:relative}
.i-banner-slide {width:100%;position:relative;}
.i-banner-slide .bd .bdimg{width:100%}
.i-banner-slide .pn{display:none!important}
.i-banner-slide .bd li{position:relative;height:auto}

banner可點擊區域計算:

        function ibannerImgWS(o, json) {
            var ibliWidth = $('.i-banner-slide').find('.bd').find('li').width()
            var obj = $(o);
            var iscale = 1;
            var ietc = ''
            if ($(window).width() < 766) {
                ietc = 'm'
                iscale = ibliWidth / 640
            }
            else {
                if (navigator.userAgent.indexOf("iPad") != -1 && ($(window).width() == 768 || 1024 || 1366)) {
                    if ((window.orientation == 180 || window.orientation == 0)) {
                        if ($(window).width() == 768) {
                            iscale = 768 / 1024;
                        }
                        if ($(window).width() == 1024) {
                            iscale = 1;
                        }
                        ietc = 'ipad-p'
                    }
                    if ((window.orientation == 90 || window.orientation == -90)) {
                        if ($(window).width() == 1024) {
                            iscale = 1024 / 1366;
                        }
                        if ($(window).width() == 1366) {
                            iscale = 1;
                        }
                        ietc = 'ipad-l'
                    }
                }
                else {
                    ietc = 'pc'
                    iscale = ibliWidth / 1920;
                }
            }
            if (!json[ietc]) {
                return false;
            }
            obj.css({
                'position': 'absolute',
                'left': Math.ceil(json[ietc][0] * iscale),
                'top': Math.ceil(json[ietc][1] * iscale),
                'width': Math.ceil(json[ietc][2] * iscale),
                'height':Math.ceil(json[ietc][3] * iscale)
            })
        }
    })();

結合調用

        var elslide = new Eononslide('.i-banner-slide');
        elslide.init({
            'pn': true,
            callback: function () {
                ibannerImgWS('.i-banner-bda-1', {
                    'pc': [left,top,width,height],
                    'm': [left,top,width,height],
                    'ipad-p': [left,top,width,height],
                    'ipad-l': [left,top,width,height],
                })
            }
        })

touch方向修正

function stopPro(obj){
    if(!obj){return;}
    var xx,yy,XX,YY,swipeX,swipeY ;
    _on(obj,'touchstart',function(event){
        var event = event || window.event;
        xx = event.targetTouches[0].screenX ;
        yy = event.targetTouches[0].screenY ;
        swipeX = true;
        swipeY = true ;
    })
    _on(obj,'touchmove',function(event){
        var event = event || window.event;
        XX = event.targetTouches[0].screenX ;
        YY = event.targetTouches[0].screenY ;
        if (swipeX && Math.abs(XX - xx) - Math.abs(YY - yy) > 0) //左右
        {
            event.stopPropagation();
            event.preventDefault();
            swipeY = false ;
        }
        else if (swipeY && Math.abs(XX - xx) - Math.abs(YY - yy) < 0) { //上下
            swipeX = false ;
        }
    })
    function _on(obj, ev, fn) {
        if (obj.addEventListener) {
            obj.addEventListener(ev, fn, false);
        } else {
            obj.attachEvent('on' + ev, function() {
                fn.call(obj);
            });
        }
    }
}

圖片預加載

jQuery.reloadimg = function () {
    var objImg = [];
    for (var i = 0; i < arguments.length; i++) {
        objImg[i] = new Image();
        objImg[i].src = arguments[i];
    }
};

// $.reloadimg('1.jpg','2.jpg')

零JQ筆記 | jquery-ui

文件結構:
external/jquery.js
jquery-ui.css
jquery-ui.js
jquery-ui.structure.css :特效、背景、邊框等
jquery-ui.theme.css :佈局 架構:

structure.css + theme.css == jquery-ui.css

包含项:

UI Core :UI核心

Core
Widget
Mouse
Position

Interactions :UI交互

Draggable:拖拽
Droppable :拖动释放
Resizable:改变层大小
Selectable:选择元素,通过鼠标拖动,划过选中
Sortable:排序交互

Widgets :控件

Accordion
Autocomplete
Resizable
...

Effects:UI特效

Effects Core
Blind Effect
Bounce Effect
...
多种效果; http://www.w3cschool.cc/jqueryui/api-easings.html
$('div').animate({'width':'100px'},1000,'特效easeOut...')

jqui里removeClass,与addClass也支持特效;

$('div').removeClass('box',1000,'easeInQuad')

并且也支持颜色

$('#div').animate({'backgroundColor':'blue'},1000)

如:show('blind',1000)

See the Pen VembrW by elmok (@elmok) on CodePen.


<script async src="//assets.codepen.io/assets/embed/ei.js"></script>

直接effect()做一次运动特效;

$('div').effect('linear',1000); 

指定中心点运动方向 direction(left|right|up|down)

$('div').toggle('blind',{direction:'left'},1000)



交互:http://www.w3cschool.cc/try/tryit.php?filename=jqueryui-api-draggable

API分為三部分:1、配置參數;2、方法;3、自定義事件


以draggable為例


1、option/Method

$('#div').draggable({
    axis:'x',
    cursor:'crosshair',
    cursorAt:{left:0,top:0},
    handle:'p'
}) //初始化

//如在以上有初始化狀態的元素下:可有:
$('#div').draggable('destroy')  //銷毀
$('#div').draggable('disable')  //禁用
$('#div').draggable('enable')   //啟用
$('#div').draggable('instance')  //獲取對象
$('#div').draggable('widget')  //获取对像 做组件的链式操作

2、Events自定義事件

$('#div2').draggable({
    axis:'x',
    create: function () {
        alert(1); //一上來初始化調1
    },
    start: function () {
        alert(2); //按下後調2
    }
})

draggable與sortable組合使用: http://jqueryui.com/draggable/#sortable


Mothed方法兩種寫法

//寫法一:
$('div').draggable('destroy')

//傳統寫法二:
var obj = $('div').draggable('instance') //得到組件對象
obj.disable()//對象下調方法 ;

Event自定義事件兩種寫法


//寫法一:
$('#div2').draggable({
    axis:'x',
    create: function () {
        alert(1); //一上來初始化調1
    },
    start: function () {
        alert(2); //按下後調2
    }
})

//寫法二:
$('#div2').on('dragcreate', function () {
    alert(2)
})

refresh

<input type="button" value="add"/>
<div id="div1">
    <p>aaa</p>
    <div>111</div>
    <p>bbb</p>
    <div>222</div>
    <p>ccc</p>
    <div>333</div>
</div>

當add即時增加高度時,必須使用refresh參數才能使用高度自動變高而不是出現滾動條;

$('#div1').accordion() //調用手風琴選項卡方法

$('input').click(function () {
    var html = $('#div1').find('div').first().html()
    $('#div1').find('div').first().html(html+'1 <br />')
    $('#div1').accordion('refresh')
})

UI控件自行查看API



UI核心

选择器
:data()
:focusable()
:tabbable()
方法
disableSelection()
enableSelection()
focus()
scrollParent()
jQuery.ui.keyCode
$('div').slice(0,2).data('name','elmok'); //給選中元素添加外部數據
$('div:data(name)').css('background','red') //使用外部數據設css

$('body').children(':focusable').css('background','red') //獲取有光標的
$('body').children(':tabbable').css('background','red') //獲取能接收tab鍵元素的;

$('div').disableSelection() //禁止選擇
$('div').enableSelection()  //開啟選擇

//1s後激活光標位置
$('input').focus(1000, function () {
    this.style.background = 'red'
}) 

//即父級必須具備滾動條才可選中,不一定要有滾動,但需具備,比如設置overflow:hidden,就不具備了;所以是overflow:auto;
$('p').scrollParent().css('background','red') 


$(document).on('keydown', function (ev) {
    if (ev.keyCode == $.ui.keyCode.ENTER) { // ev.keyCode == 13
        alert('回車')
    }
})

position()

<div id="div1">
    <div id="div2"></div>
</div>
    $(function () {
        $('#div2').position({
            my: 'left bottom', //div2內層基點居中
            at: 'right bottom',//div1外層基點
            of: '#div1'//div1外層指定元素
        })
    })

<h2>Widget Factory</h2>

//比如,創建一個方法:testProgressBar(),調用是使用下面這種形式:

$('#div1').testProgressBar({value: 20});

//所以架子應該是:
$.widget('eonon.testProgressBar'{ //不能直接寫,防止衝突 需要加命名空間;
    options:{},
    _create:function(){}
})

稍微豐富點

    $('#div1').testProgressBar({
        value: 20,ut:'px',color:'red'       //value,ut,color作為配置參數
    });


$.widget('eonon.testProgressBar'{ //不能直接寫,防止衝突 需要加命名空間;
    options:{
              value: 0,
              ut: '%',
              color:'pink'
},
    _create:function(){
            var progress = this.options.value + this.options.ut;
            this.element.html(progress).css('color',this.options.color) //this.element == div1
}
})

$.widget(方法名,json擴展)


http://api.jqueryui.com/mouse/


$.ui.mouse指繼承方法,如果不是自定義事件則可不寫


http://api.jqueryui.com/jQuery.widget/#method-_create


自定義事件作為options參數接收;_create:function(){初始化};_mouseUp:function(){接收}


_mouseUp需要在_create裏初始化this._mouseInit()




$(function () {
    $.widget('eonon.testProgressBar', $.ui.mouse , { //不能直接寫,防止衝突 需要加命名空間;  
        options: { //收集配置參數
            value: 0,
            ut: '%',
            color:'pink',
            customMouseUp: function () {} //自定義事件即作為options的屬性,再使用_mouseUp這個默認up方法調用即可
        },
        _create: function () {
            var progress = this.options.value + this.options.ut;
            this.element.html(progress).css('color',this.options.color) //this.element == div1
            this._mouseInit()
        },
        _setOption: function (a,b) { //進行設置操作時走這裏
            //alert(a) //value
            //alert(b) //80

            if(a == 'value'){
                this.element.html(b+this.options.ut)
            }
        },
        aaa: function () { //共用方法,
            alert('aaa')
        },
       _aaa: function () { //帶下劃線是私有方法,外部找到;
            alert('_aaa')
        },
        _mouseUp: function () {
            //alert('_mouseUp')
            this.element.trigger('m.customMouseup')
            this.options.customMouseUp()
        }
    });

    $('#div1').testProgressBar({
        value: 20,ut:'px',color:'red'//value作為配置參數
        ,customMouseUp: function () { //自定義事件;
            alert('觸發了參數定義的mouseUp')
        }
    });

//調用自定義方法:

    $('#div1').on('m.customMouseup', function () {
        alert('on帶up時觸發')
    })
/*
$('#div1').testProgressBar('aaa') //正常彈出
$('#div1').testProgressBar('_aaa') //無法彈出 ,私有
*/

    })

零JQ筆記 | 組件小例

架子:

$(function () {
        var t1 = new Tab();
        ti.init('div1', {})
    })

    function Tab() {
        this.settings = { //默認參數
            event: 'click'
        }
    }
    Tab.prototype.init = function (_parent, opt) {
        $.extend(this.settings, opt);


    }

主要分離3方面:


配置參數:opt:events , delay


方法:methos:nowSel(),getContent


事件:beforeClick,afterClick


注意的點:

1、jq中主動解發 $(_this).trigger('afterClick'),相當於 autoEvent(_this, 'afterClick') ;


2、特別留意this指向問題;


3、jq中$.extend(this.settings, opt),相當於 extend(this.settings, opt)


    $(function () {
        var t1 = new Tab();
        t1.init('div1', {})
        var t2 = new Tab();
        t2.init('div2', {
            event:'mouseover'
        })

        var t3 = new Tab();
        t3.init('div3', {
            event:'mouseover',
            delay:200
        })
        var t4 = new Tab();
        t4.init('div4', {})
        t4.nowSel(2)
        $('#inp1').click(function(){
            console.log(t4.getContent());
        })

        $(t4).on('beforeClick', function () {
            console.log(t4.getContent() + ' before');
        })
        $(t4).on('afterClick', function () {
            console.log(t4.getContent() + ' after');
        })

    })

    function Tab() {
        this._parent = null;
        this._inp = null;
        this._div = null;
        this.cur = 0;
        this.settings = { //默認參數
            event: 'click',
            delay:0
        }
    }
    Tab.prototype.init = function (_parent, opt) {
        $.extend(this.settings, opt);
        this._parent = $('#'+_parent);
        this._inp = this._parent.find('input');
        this._div = this._parent.find('div');
        this.change();
    }
    Tab.prototype.change = function () {
        var _this = this;
        var _t = null;
        this._inp.on(this.settings.event,function(){

            var This = this;
            if(_this.settings.event == 'mouseover' && _this.settings.delay){
                _t = setTimeout(function(){
                    show(This)
                },_this.settings.delay);
            }
            else{
                show(this)
            }
        }).mouseout(function () {
            clearTimeout(_t);
        })
        function show(obj){ //obj指按鈕;

            $(_this).trigger('beforeClick') ; //點擊前

            $(obj).attr('class','active').siblings().removeClass('active');
            _this._div.eq($(obj).index()).css('display','block').siblings('div').css('display','none')
            _this.cur = $(obj).index()  //千萬注意this指向,坑

            $(_this).trigger('afterClick') ; //點擊前
        }
    }
    Tab.prototype.nowSel = function(index){
        this._inp.eq(index).attr('class','active').siblings().removeClass('active');
        this._div.eq(index).css('display','block').siblings('div').css('display','none')
        this.cur = index;
    }
    Tab.prototype.getContent = function () {
        return this._div.eq(this.cur).html()
    }

http://tangram.baidu.com/magic/

零JQ筆記 | ajax

AJAX

callback返回三个参数,在load()方法中,只要请求完成,无法是否成功,callback即会被触发

$('#resText').load('test.html .para', function (responseText, textStatus, XMLHttpRequest) {
  console.log(responseText); //请求返回的内容
  console.log(textStatus); //请求状态:success,error
  console.log(XMLHttpRequest); //XMLHttpRequest对象
});

$.get()/$.post()
$.get(url ,data[,type])

$.get(url, 发送到服务器的key/v, 回调,服务器返回格式xml/html/script/json/text/_default)

发送到get1.php,发送的内容为:username/content/,要求服务器返回html格式;

$.get('get1.php', {
  username: $('#username').val(),
  content: $('#content').val()
}, function (data, textStatus) {
  $('#resText').html(data); // 把返回的数据添加到页面上
}
);

function (data, textStatus): data:返回的内容:xml/json/html等; testStatus: 请求状态:success/error/notmodified/timeout; 而且只有当数据成功返回success反才调用,注意与load()不一样;

data返回的数据内容如

返回内容 处理
html 可直接输出$(obj).html()
XML XML文档可使用常用的attr()/find()/filter()等处理
function (data, textStatus) {
  var username = $(data).find('comment').attr('username');
  var content = $(data).find('comment content').text();
  var txtHtml = '<div class=\'comment\'><h6>' + username + ':</h6><p class=\'para\'>' + content + '</p></div>';
  $('#resText').html(txtHtml); // 把返回的数据添加到页面上
}

</td>

</tr> 
<tr> 
 <td>json</td> 
 <td>json格式简洁,易读,对返回处理后输出html
function (data, textStatus) {
  var username = data.username;
  var content = data.content;
  var txtHtml = '<div class=\'comment\'><h6>' + username + ':</h6><p class=\'para\'>' + content + '</p></div>';
  $('#resText').html(txtHtml); // 把返回的数据添加到页面上
},
'json'); //要求服务器返回json格式

</td>

</tr> 

</tbody>
</table>


好处与利弊:html片段最简单;json数据重用、性能、大小、较好; xml远程应用程序未知时较好,适用于任何语言;



$.getScript('test.js')
当然,也有回调:

$.getScript('test.js',function(){
    $('#go').click(function(){
    .....
})
})



$.getJSON('test.json')
当然,也有回调:

$.getJSON('test.json',function(data){
   //data返回数据
})
})



通过$.getJSON得到的数据data,可使用$.each()来遍历[对象和数组]

$.each(data, function (i, elem) {
console.log(i); //i表示索引,elem表示值
console.log(elem['username']);
})
通过JSONP加载其它网站数据;跨域首选

$.getJSON('http://api...../',function(data){
   $.each(data[obj],function(i,elem){
        .....
        //i可作为判断条件,退出each循环,return false;
    })
})

底层$.ajax(options)方法

<style>

.ajax-tb-1 { border-collapse: collapse }
.ajax-tb-2{border-collapse: collapse}
.ajax-tb-2 td{border:1px solid #ddd;padding:5px 10px;line-height: 2;}
.ajax-tb-2 tr>td:nth-of-type(2){white-space: nowrap; }
.ajax-tb-1 td, .ajax-tb-1 th { border: 1px solid #ddd; padding: 5px 10px; line-height: 2; }

</style>

該方法只有一個參數,所有包含在$.ajav()裏,參數以key/value形式,所有參數除url外都是可選

參數名 類型 說明
url string 默認,發送,請求地址
type string post/get,默認get,注意put/delete部分瀏覽器不支持
data obj or string 發送到服務器的數據,如非字符串,則自動轉字符串形式 <br/>請求獎附加在url後,防止自動轉可查看processData選項,對象必須為key/value格式;<br/>例如 {fool:'bar1',foo2:'bar2'} ==>>&foo1=bar1&foo2=bar2 <br/>如果是數組,轉為不同值對應同一個名稱。 {foo:['bar1','bar2']}==>>&foo=bar1&foo=bar2
dataType string 預期服務器返回類型,不指定:自動按http包mime信息返回responseXML或responseText,並作為callback參數傳遞;可用類型:<br/>xml:返xml文檔,可用jq處理 <br/>html:純html信息,包含的script標籤會在插入dom時執行<br/>script:純js代碼,不自動緩存結果,除非設置cache,注意:遠程請求時所有跨域請求都轉為get請求 <br/>json:返回JSON數據;<br/>jsonp:使用JSONP形式調用函數時,如:myurl?callback=?,jq將自動替換後一個?為正確函數名 <br/>text:純txt字符串
beforeSend Function 發送前可修改XMLHttpRequst對象函數,如:添加算定義HTTP頭,在beforeSend中返回false可取消本次ajax請求,XMLHttpRequest對象是惟一請求;<br/> function(XMLHttpRequest){ this //調用本次ajax請求傳傳遞的options參數 }
complete Function 請求完成後回調,成功失敗都可調用;<br/>參數:XMLHttpRequest對像和一個描述成功請求類型的string, function(XMLHttpRequest,textStatus){ this //調用本次ajax請求傳傳遞的options參數 }
success Function 請求成功後callback <br/> 1).由服務器返回,按給的dataType參數進行處理後數據 ; <br/>2).描述狀態string; <br/> function(data,textStatus){ data; //可能是xmlDoc,jsonObj,html,text等等, this; //調用本次ajax請求傳傳遞的options參數 }
error Function 請求失敗時調用,3參數: function(XMLHttpRequest ,textStatus,errorThrown){ //通常情況下textStatus和errorThown只有其中一個包含信息 this //調用本次ajax請求傳傳遞的options參數 }
global Boolean 默認true,表示是否觸發全局ajax事件,設置false將不觸發,AjaxStart或AjaxStop可用於控制各種Ajax事件;

代替$.getScript()

$(function () {
    $('send').click(function () {
        $.ajax({
            type:'GET',
            url:'test.js',
            dataType:'script'
        })
    })
})

代替$.getJSON()

$.ajax({
    type:'GET',
    url:'test.json',
    dataType:'json',
    success: function (data) {
        var html=''
        $.each(data, function (index,elems) {
            html +=index 
            +':' 
            +elems['username'] 
            +':' 
            +elems['content']
        })
        $('body').html(html)
    }
})

test.json

[
  {
    "username": "张三",
    "content": "沙发."
  },
  {
    "username": "李四",
    "content": "板凳."
  },
  {
    "username": "王五",
    "content": "地板."
  }
]



1、serialize()方法,表單序列化,所有元素必須設置name,使用name來獲取;

<form action="" id="f2">
    <p>user:<input type="text" name="user" id=""/></p>
    <p>password:<input type="password" name="pws" id=""/></p>
    <input type="checkbox" name="ck" id=""/>
    <input type="checkbox" name="ck2" id=""/>
    <input type="radio" name="rrr" id=""/>
    <input type="radio" name="rrr" id=""/>
    <input type="radio" name="rrr" id=""/>
    <p><input type="button" id="send2" value="提交"/></p>
</form>
$('#send2').click(function () {
    console.log($('#f2').serialize());
    console.log($('#f2').serializeArray()); //若使用serializeArray()輸出對像如下圖
})

輸出:user=elmok&pws=elmokpws&ck2=on&rrr=on

輸出對象:

所以可使用$.each()

var fdata = $('#f2').serializeArray(),
$.each(fdata ,function(i,elems){
    $('body').append(fdata.value + '')
})

例子:

<form id="form1" action="#">
    <p>评论:</p>
    <p>姓名: <input type="text" name="username" id="username" /></p>
    <p>内容: <textarea name="content" id="content"  rows="2" cols="20"></textarea></p>
    <p><input type="button" id="send" value="提交"/></p>
</form>
<div id="resText"></div>

為取得姓名和內容,必須將字段一個個添加到data參數中

$('#send').click(function () {
    $.get('get1.php',{
        username:$('#username').val(),
        content:$('#content').val()
    }, function (data, textStatus) {
        $('#resText').html(data)  //返回頁面
    })
})

少量可以,多則使用serialize()方法

$('#send').click(function () {
    $.get('get1.php',$('#form1').serialize(), function (data, textStatus) {
        $('#resText').html(data)
    })
})

需要注意:$.get()方法中,data參數不僅可使用映射方式:

{
username:$('#username').val(),
content:$('#content').val()
}

也可使用字符串[中文問題]方式:注意,字符串無{}號

$('#send').click(function () {
    $.get('get1.php',
 "username="+encodeURIComponent($('#username').val())+"&content="+encodeURIComponent($('#content').val())     
    , function (data, textStatus) {
        $('#resText').html(data)
    })
})



3、$.param()方法
serialize()方法核心,對一個arr或obj按照key/value進行序列化

var obj = {a:1,b:2,c:3}
var k = $.param(obj)
//輸出:a=1&b=2&c=3



jq中的ajax全局事件
加載中loading....提示,定義好
loading......

$("#loading").ajaxStart(function(){
  $(this).show();
});
$("#loading").ajaxStop(function(){
  $(this).hide();
});

其他地方使用,仍有效,因為是全局;

另外幾個方法


ajaxComplete(fn..):請求完成時執行;

ajaxError(fn..):發生錯誤時執行,捕捉到錯誤可作為最後一個參數傳遞;

ajaxSend(fn..):請求發送前執行;

ajaxSuccess(fn...):請求成功時執行;

1、jq1.5之前,如不想某個ajax請求受全局方法影響

$.ajax({
    url:'...',
    global:false
})

1、jq1.5之後,如不想某個ajax請求受全局方法影響,則在每次發送請求之前設置

$.ajaxPrefilter(function (options) {
    options.global = true;
})

零JS筆記 | 記憶點二

取值,只會取第一位、賦值,則是全部改變


filter:過濾;not:排除

注意:filter与has的区别,filter是针对当前操作元素,has是针对当关操作元素里面的东西;包含的意思

    //$('.box').filter('[title=one]')
    //取值时:当集合,只会取到第一位
    console.log($('li').html());
    //赋值时,则是全部改变
    $('li').html('aaa')
    //filter not,相反
    $('div').filter('.box').css('background','red')
    $('div').not('.box').css('background','red')
    //has 包含元素
    $('div').has('span').css('background','red')

next()與prev():緊跟相鄰元素【必要條件】,如果帶參數,也必須是緊跟相鄰元素,如果操作下一個選擇類名,必須使用nextALl()/prevAll()

注意:index():當前元素在所有兄弟節點的位置,不帶參數時與標籤或類id等無關

<h1></h1>
<h5></h5>
<h3 id='h'></h3>
<h2></h2>

$('#h').index() //2

width(): width

innerWidth():width+padding

outerWidth():width+padding+border

outerWidth(true):width+padding+border+margin


offsetLeft獲取不到隱藏的值 ;如果div.style.display = 'none'

$('div').get(0).offsetWidth  //0 
$('div').outerWidth() // 100,可獲取到隱藏元素

insertBefore/insertAfter; appendTo,prependTo動詞

$('span').insertBefore('div') //操作span在div前面
$('span').insertAfter('div') //操作span在div後面

before ,after, append ,preend,名詞

$('span').before('div') //span的前面必須是div
$('span').after('div') //span的後面必須是div

offset()獲取到屏幕的距離,注意與offsetleft的區別(offsetleft到有定位父級的元素,如果獲取到屏幕的距離 需)

    function getPos(obj){
        var pos = {left: 0, top:0};
        while (obj) {
            pos.left +=obj.offsetLeft;
            pos.top +=obj.offsetTop;
            obj = obj.offsetParent
        }
        return pos;
    }

position(),當使用position()時,相當於被操作元素加個定位,注意本身被操作元素的margin值不影響的,即到有定位的父級

    console.log($('div').position().left);
    //到有定位的父級的left值,把當前元素轉換為定位的形式,所以margin是不影響的,因為定位元素的left及top值

parent():獲取父級(不管是否有定位)

offsetParent():獲取有定位的父級<br />對應 offsetNode</p>

jq寫drag

    $(function () {
        var disX = 0;
        var disY = 0;
        $('div').mousedown(function (e) {
            disX = e.pageX - $(this).offset().left;
            disY = e.pageY - $(this).offset().top;
            $(document).mousemove(function (e) {
                $('div').css({'left': e.pageX - disX});
                $('div').css({'top': e.pageY - disY});
            })
            $(document).mouseup(function () {
                $(document).off()
            })
        })
        return false;
    })

fadeTo(時間,透明度)

get(),jq轉原生:$('#div1').get(0).innerHTML;get()如果不加參數,相當於轉成一組集合;

for(var i=0;i<$('li').length;i++){
    $('li').get(i).style.background = 'red'
}

更簡單的,加上[i]則自動轉為原生

for(var i=0;i<$('li').length;i++){
        $('li')[i].style.background = 'red' 
    }

text(),當選擇為一組元素集合時;會獲取到所有的內容,而html()只會獲取到集合中的第一個;

remove(),刪除的元素返回值即被刪元素;所以 var _div = $('div').remove()


detach()跟remove()一樣,但會保留事件;


parents():获取当前元素的所有祖先节点,参数就是筛选功能

closest():获取最近的祖先节点,包括自身,必须写参数

Until()截止的意思:
nextUntil('h2'),当走到h2包括h2自身都不会走下去;

类似有:parentsUntil()、nextUntil()、prevUntil()

clone()

$('div').clone().appendTo( $('body') )

wrap():包装方法

$('span').wrap('<b></b>')

//<b><span></span></b>
//<b><span></span></b>
$('span').wrapAll('<b></b>')

//<b><span></span><span></span></b>

wrapInner内部包装

$('span').wrapInner('<b></b>')

//<span><b></b></span><span><b></b></span>

unwrap():删除包装、删除父级;不包括body

<span></span>
<div><span></span></div>

====>>
$('span').unwrap()
//结果:把span的父级删除
<span></span>
<span></span>

add():添加组合:使用两个不同标签或类的组合在一起可一次性设置相同的属性,如背景

//使用span 及div 的背景色都为yellow;
    var elem = $('div')
    var elem2 = elem.add('span')
    elem.css('color','red')
    elem2.css('background','yellow') //div及span

slice():截取一组元素的前几位;

$('li').slice(1,4).css('background','red')
    //截止起始到终止的元素,不包括终止元素,即截取前3个;

serialize():数据串连:序列化

<form>
    <input type="text" name="a" id="" value="1"/>
    <input type="text" name="b" id="" value="2"/>
    <input type="text" name="c" id="" value="3"/>
</form>

console.log($('form').serialize());
//string: a=1&b=2&c=3

数组形式:serializeArray()

 console.log($('form').serializeArray());

 [ { name="a",  value="1"},  { name="b",  value="2"},  { name="c",  value="3"}]

animate({},时间,运动形式,回调)

    //先走宽再走高;
    $(this).animate({width: 300}, 1000).animate({height: 300}, 2000)

stop():默认只会阻止当前运动;

stop(true):阻止后续运动;
stop(true,true):可以立即停止到指定的目标点;
finish():立即停止到所有目标点上;

    //先走宽再走高;
    $(this).animate({width: 300}, 1000).delay(1000).animate({height: 300}, 2000)

事件委托,注意顺序区别,on要先写动作'click',再写被点击元素,delegate则相反,顺序写反不能生效


取消分别为off(),undelegate()

$('ul').on('click','li',function(){   //on(动作,元素,函数)
    this.style.background = 'red'
})
//或
$('ul').delegate('li','click',function(){ //delegate(元素,动作,函数)
    this.style.background = 'red'
})

trigger()主动触发; 当然主要用在自定义事件上;

$('box').trigger('click');

$('div').on('show',function(){
    alert(1)
})
$('div').trigger('show')

ev.data /ev.target / ev.type

//ev.data点击时传参;ev.data == json整体 
$('#div1').on('click', {name: 'hello'}, function (ev) {
    alert(ev.data.name)
})

//ev.target当前操作事件源;
$('#div1').on('click', function (ev) {
    ev.target.style.background = 'red'   //当前操作变红;
})
//ev.type
$('#div1').on('click', function (ev) {
    alert(ev.type)  //click
})


$.下的常用方法;工具方法


$.(),$().html(),$().val()等,只能给JQ对象用


$.xxx..不带括号;不仅可给JQ用,也可给原生用,工具方法;

$.type

var a = 'hello'
console.log(typeof a); //原生: string
console.log($.type(a)); //JQ: string  比原生可判断更多类型;
console.log($.type(new Date)); //data
console.log($.type({})); //obj
console.log($.type([])); //array
console.log($.type(null)); //null

$.trim(str),去前后空格;

$.inArray(),类似于indexOf

var arr = ['a','b','c','d']
console.log($.inArray('b', arr));  //1,b的位置第二位,如果找不到则返回-1

$.proxy():改变this指向;$.proxy(函数名,要改的this指向位置)()最后再调用,否则不会运行;

function show(){
    alert(this)
}
//  show()  //window

$.proxy(show,document)()

//传参的情况;
function show(n1,n2){
    alert(n1)
    alert(n2)
    alert(this)
}
//    show()  //window
$.proxy(show,document)(3,4)
//$.proxy(show,document,3,4)()
//$.proxy(show,document,3)(4) 
传参的位置都改;

//比如: 
$(document).click(show)  //默认是document

//更改为window
$(document).click($.proxy(show,window))

//事件的传参只能写在里面,写在外面则直接执行了(不需要点击执行,不是要的效果)

$(document).click($.proxy(show,window,3,4))

$.noConflict():防止冲突

    var mm = $.noConflict();
    var $ = 10;  //被10占用时
    mm(function () {
        
    })

$.parseJSON():把字符串解析成JSON类型

var str  = '{"name":"hello"}'
console.log($.parseJSON(str));

//所以:$.parseJSON(str).name即可找到'hello'

$.makeArray():把类数组转成真正的数组

//比如:
    var _div = document.getElementsByTagName('div')  //类数组
    _div.push();
//虽然是集合,但并不是真正的数组,所以不能push

  $.makeArray(_div).push('a')

$.ajax({})

$.ajax({
    type:'POST',
    url:'xxx.php',
    dataType:'json',
    success: function (data) {
        alert(data);
    },
    error:function(){
        alert(2)
    }
})

$.get(url,{},成功的回调)


$.post(url,{},成功的回调)


$.getJSON(url,{},成功的回调),支持JSONP形式:指定?callback=?; jsonp需要一个函数名;

$.getJSON('xxx.php?callback=show',function(){
});
show()

插件的使用


$.extend()://工具方法下的形式;

$.fn.extend()// 扩展到jq对象下的形式</p>
$.extend({
    leftTrim: function (str) {
        return str.replace(/^\s+/,'')
    },
    rightTrim:function(){},
    aaa:function(){alert(1)},
    bbb:function(){}
})

//调用
$.leftTrim(str)
$.aaa() //1
$.fn.extend({
    drag:function(){
        var disX = 0;
        var disY = 0;
        var _this = this;
        this.mousedown(function(e){
            disX = e.pageX - $(this).offset().left;
            disY = e.pageY - $(this).offset().top;
            $(document).mousemove(function(e){
                _this.css('left', e.pageX - disX);
                _this.css('top', e.pageY - disY);
            })
            $(document).mouseup(function(){
                $(this).off()
            })
            return false
        })
    },
    aaa:function(){
        alert(2)
    }
})

//调用:$('#div1').drag()
//$().aaa(); //2



超简单版vquery


$()类似于函数调用,即$是函数名;

1、$('div')===> function $(vArg){ } //vArg表示不定类型的参数;


2、$().css(),函数调用函数? ===》类似于创建面面对像:var arr = [] ; arr.push();<br />对像.函数(),所以,要使用$()是一个对象;

function $(vArg){
    return object;
}

使用对象必须创建构造函数,所以架子是:

function Vquery(vArg){
var this.elements = [] //存的是$()里的东西
    
}

Vquery.prototype.css = function(){};
Vquery.prototype.html = function(){};

function $(vArg){
    return new Vquery(vArg);
}
//必须传参才能使用,重点是返回对象;

未作容错


function bindEvent(obj, events, fn) {
    if (obj.addEventListener) {
        obj.addEventListener(events, function (e) {
            //fn() -- > false
            //不写return false ===> undefined
            //undefined == false == >返回false
            if (fn() == false) {
                e.preventDefault();
                e.cancelBubble = true; //冒泡
            }
        }, false)
    }
    else {
        obj.attachEvent('on' + events, function () {  //IE下
            if (fn() == false) {
                window.event.cancelBubble = true; //IE下阻止冒泡
                return false;//IE下阻止默认事件
            }
        })
    }
}
function getByClass(_parent, sClass) {
    var arr = [];
    var elems = _parent.getElementsByTagName('*')
    for (var i = 0; i < elems.length; i++) {
        if (elems[i].className == sClass) {
            arr.push(elems[i])
        }
    }
    return arr;
}
function getStyle(obj, attr) {
    return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj, false)[attr];
}
function toArray(elems) {
    var arr = []
    for (var i = 0; i < elems.length; i++) {
        arr.push(elems[i])
    }
    return arr;
}
function Vquery(vArg) {
    this.elements = []
    switch (typeof vArg) {
        case 'function':
            bindEvent(window, 'load', vArg);
            break;
        case 'string':

            switch (vArg.charAt(0)) {
                case '#':
                    this.elements.push(document.getElementById(vArg.substring(1)));
                    break;
                case '.':
                    this.elements = getByClass(document, vArg.substring(1));
                    break;
                default :
                    this.elements = toArray(document.getElementsByTagName(vArg)) //类数组 ,所以类型改变了,to为了保持this.elements的类型;
                    break;
            }
            break;
        case 'object' ://vArg.constructor == Array //注意不加引号
            if (Object.prototype.toString.call(vArg) == '[object Array]') {

                this.elements = vArg;
            } //如果得到的object是数组,则再push变成复合数组[[]],所以需要处理;
            else {
                this.elements.push(vArg);
            }
            break;
    }
}

Vquery.prototype.html = function (str) {
    if (str) {
        for (var i = 0; i < this.elements.length; i++) {
            this.elements[i].innerHTML = str;
        }
    }
    else {
        return this.elements[0].innerHTML;
    }
    return this;
}
Vquery.prototype.click = function (fn) {
    for (var i = 0; i < this.elements.length; i++) {
        bindEvent(this.elements[i], 'click', fn)
    }
    //this.on('click',fn)
    return this;
}
Vquery.prototype.mouseover = function (fn) {
    for (var i = 0; i < this.elements.length; i++) {
        bindEvent(this.elements[i], 'mouseover', fn)
    }
    //this.on('mouseover',fn)
    return this;
}
Vquery.prototype.on = function (event, fn) {
    for (var i = 0; i < this.elements.length; i++) {
        bindEvent(this.elements[i], event, fn)
    }
    return this;
}
Vquery.prototype.hide = function () {
    for (var i = 0; i < this.elements.length; i++) {
        this.elements[i].style.display = 'none'
    }
    return this;
}
Vquery.prototype.show = function () {
    for (var i = 0; i < this.elements.length; i++) {
        this.elements[i].style.display = 'block'
    }
    return this;
}
Vquery.prototype.hover = function (fnIn, fnOut) {
    this.on('mouseover', fnIn);
    this.on('mouseout', fnOut)
    return this;
}
Vquery.prototype.css = function (attr, value) {
    if (arguments.length == 2) {  //设置

        for (var i = 0; i < this.elements.length; i++) {
            this.elements[i].style[attr] = value;
        }
    }
    else if (arguments.length == 1) {  //获取
        if (typeof attr == 'object') {   //注意理解此处
            for (var j in attr) {
                for (var i = 0; i < this.elements.length; i++) {
                    this.elements[i].style[j] = attr[j];
                }
            }
        }
        else {
            return getStyle(this.elements[0], attr)
        }
    }
    return this;
}
Vquery.prototype.attr = function (attr, value) {
    if (arguments.length == 2) {  //设置
        for (var i = 0; i < this.elements.length; i++) {
            this.elements[i].setAttribute(attr, value);
        }
    }
    else if (arguments.length == 1) {  //获取
        return this.elements[0].getAttribute(attr);

    }
}
Vquery.prototype.eq = function (num) {
    //return this.elements[num];  //this.elements获取到的都是原生的;所以
    return $(this.elements[num])   //转换对象;
}
Vquery.prototype.index = function () {
    var elems = this.elements[0].parentNode.children; //先找当前选中的父节点,再找子节点可得出同辈所有;
    for (var i = 0; i < elems.length; i++) {
        if (elems[i] == this.elements[0]) {
            return i;
        }
    }
}
Vquery.prototype.siblings = function () {
    var arr = []
    var elems = this.elements[0].parentNode.children; //先找当前选中的父节点,再找子节点可得出同辈所有;
    for (var i = 0; i < elems.length; i++) {
        if (!(elems[i] == this.elements[0])) {
            arr.push(elems[i])
        }
    }
    return $(arr)
}

Vquery.prototype.find = function (sel) {
    var arr = [];
    if (sel.charAt(0) == '.') { //.class
        //这里的this.elements存的是$()里面的东西
        for (var i = 0; i < this.elements.length; i++) { //循环每一个ul里
            arr = arr.concat(getByClass(this.elements[i], sel.substring(1)));
            //每一个ul -->  this.elements下可能会有多个li,
            //比如,第一次找个2个,第2次找到3个,所以需使用数组concat方法
            //注意此次不能使用push,因为 getByClass方法得到的即为数组;
            //2,也不能简单 =  因为比如第2次得到3个会覆盖第一次得到的2个,
            //所以,使用arr.concat
        }
    }
    else { //tag
        for (var i = 0; i < this.elements.length; i++) {
            arr = arr.concat(toArray(this.elements[i].getElementsByTagName(sel))) //类数组转
        }
    }
    return $(arr); //同样是原生的,所以需要使用 $(arr)
}

function $(vArg) {
    return new Vquery(vArg) //返回对象
}

$.trim = function (str) {
    return str.replace(/^\s+|\s+$/g,'')
}
$.proxy = function(){}
$.makeArray = function(){}
$.inArray = function(){}


$.extend = function(json){
    for(var attr in json){
        $[attr] = json[attr]
    }
}
$.fn = {}
$.fn.extend = function(json){
    for(var attr in json){
        Vquery.prototype[attr] = json[attr]
    }
}

插件扩展


工具写法:$.extend(); JQ对象写法:$.fn.extend()

      $.extend({

            aaa:function(){
                alert(1)
            },
            bbb:function() {
                alert(2)
            }

        })
        $.aaa() //1
        $.bbb() //2


//必须扩展到Vquery的原型下;
        $.fn.extend({

            aaa:function(){
                alert(4)
                return this;
            },
            bbb:function() {
                alert(5)
                return this;
            }

        })
         //4
        $().bbb().aaa() //5

零JQ筆記 | 記憶點一

1、jq先引入,base後引入,則$歸base所有,所以可定義一個來使用jquery

var $fn = jQuery; 
$(function(){
  alert($fn('#box'))
})

//或直接 
alert(jQuery('#box'))

2、jq後引入,則$歸jq,所以jq提供一個方法來剔除本身的$

jQuery.noConflict(); 
var $fn = jQuery
alert($fn('#box'))



選擇器


jq獲取id時,無論頁面上有多少個都只返回1個;

$('.box>p') ===  $('.box').children('p')  //即只看子選擇,孫子後失明
$('.box+p') === $('.box').next('p')
$('.box~p') === $('.box').nextAll('p')
find()/next()/nextAll()/children() 1、如果不傳參,相當於find('*'),影響性能,建議傳參 2、性能高於高級選擇器 $('.box').find('p'),性能最好 $('p','.box'),轉成1,慢5%-10% $('.box')children('p'),慢50% $('.box>p')慢70% $('.box p')慢77% $('p',$('.box'))慢23% var box = $('.box'); var p=box.find('p');性能會提升 如jq有提供獨立的方法,優先推薦使用

pervUntil / nextUntil

$('.box').pervUntil('p').css() 
$('.box').nextUntil('p').css() //與.box同級,一直向下搜索,遇到p以前的所有元素都被css選中

a[title|=num] 具有這個屬性,或開頭屬性匹配後面一個 - 號的DOM
a[title!=num] 不等於這個屬性
a[title~=num] 具有這個屬性,且以空格分割的屬性
aabc 選取class=box,且存在bbb這個屬性

:not(.box)選取class不是box
:first :last需要指明哪個元素是父元素
:has(.box)選取有class為box
:parent選取有子元素或文本的元素

.has(.box)可提高性能
.parentsUntil('div'),遇到div父元素停止

:hidden
:visible

$('li:first-child')獲取每個父元素的第一個子元素

其他方法 :

.is(s/o/e/f)
.hasClass()
$('li').slice(0,2),選取從start到end位置的元素

$('div').contents() 獲取某個元素下面所有節點,包文本,如是iframe,則可查找文本內容

$('div').filter('.box')選擇div下面的.box元素

當然 ,filter也支持fn操作

$('div').filter(function(){
return ......
})



DOM操作


attr()裏的function(){}可不傳參,或只傳一個index,表示當前元素的索引0開始,
html(),text(),val(),is(),filter(),都可以使用使用fn返回,如集合,則可以傳index來獲取索引;
如:

$('#ul1 li').attr('class', function (index) {
    return 'pro'+index

})
removeAttr('title'),无法传递index 及 value
var boxColor = $('.box').css(['width','height','color'])
for(var i in boxColor){
  alert(i+'boxColor[i]')
}

特别留意:标签与class同名时:index相加,即两个对象要获得一一匹配,则需要传参数过滤类型:如:

<h5>hhhhhhhhhhhhhhh</h5>
<div class='h5'>dididididididididid</div>
<h5>hhhhhhhhhhhhhhh</h5>
<div class='h5'>dididididididididid</div>
        var _sh5 = $('*').find('h5');
        var _sch5 = $('*').find('.h5');
        _sh5.on('click',function(){
                _sch5.eq($(this).index('h5')).stop().slideToggle();
        });


$.each操作原生數組 :

var arr = [1,2,3] //原生数组
var arrN = []
$.each(arr, function () {
   arrN.push(this+'1') //this指每个值
})
console.log(arrN);  [11,21,31]

$(function () {
    $('li').each(function (i, e) {
    console.log(i+':' + e.innerHTML);  
//注意,e代表DOM 元素,所以是js的方法innerHTML,不能使用html()
    })
})

var count = 0;
$('box').click(function () {
    $(this).toggleClass('red',count++%3==0)  
//传参数,返回布尔,点2次切换,相当于频率参数
})

特殊方法:

$('li').css('width', function (i, v) { //i表示索引,v表示当前dom所对应的属性值
    return (parseInt(v)-50)+'px'
})


$('.box').width() //不包

$('.box').innerwidth() //包内边距

$('.box').outerWidth() // padding+border

$('.box').outerWidth(true) //padding+border+margin

$('.box').offset().left //相对视口
$('.box').position().left //相对父元素
$(window).scrollTop() //滚动条位置



DOM节点

$('.box').append(function (i, html) {  //html表示.box未插入前原有的内容,不包括.box标签
    console.log(html);
    return '<strong>节点</strong>'
})

$('.box').prepend(function (i, html) {
    console.log(html);
    return '<strong>节点</strong>'
})

$('.box').wrapInner(function () {    //向box里的内容用<b></b>包起来
    return '<b>bbb</b>'
})

wrap() wrapAll(),前面把每个元素当成一个独立体,后者作为整体包住

$("button").click(function(){  //删除每个p的父级元素;
  $("p").unwrap();
});

.remove('.box'),移除指定.box
.datach()保留事件;
.empty()

节点被替换后所有事件都消失
$('.box').replaceWith('<strong></strong>') === $('').replaceAll($('.box')) 返回结果不同,[链式],返回都是所操作的元素,即第一个元素;
另:reference = element.replaceChild(newChild,oldChild)



表單


如果是表单元素都必须含有name属性

:image所有图像按钮
:file所有文件按钮
:hidden所有不可见字段
$(':input')

:enabled 所有可见
:disabled 所有不可用
:checked 单选和复选
:selected 下拉



基础事件


注意:bind在1.7版本後推薦使用整合on

$('input').bind('mouseout mouseover',function(){  //移入移出分别执行一次
  $('div).html(function(i,v){
    return v+ '1'
  })
})

$('input').bind({
  'mouseout':function(){
    alert('out')
  },
  'mouseover':function(){
    alert('over')
  }
})

select()文本选定时触发,
change()文本改变时触发
submit(),在定要在form作用内才能触发;
mouseover mouseenter 穿过子节点是否触发
unload()新版不支持 ie支持 ,chrome不支持,一般用于清理工作;


keydown keyup返回键码,keypress返回字符编码;事件对像的keycode
keypress 返回的是字符编码,使用charCode

$('#i2').keyup(function (e) {
    console.log(e.keyCode);  //65 键码 
})

$('#i2').keypress(function (e) { //97 字符编码
    console.log(e.charCode);
})


hover == mouseenter mouseleaver
focus blur 必须是当前元素触发
focusin focusout 穿過子元素也會觸發,相當於mouseover mouseenter的區別;

//1.7後刪除的toggle切换功能,替換實現; 
var flag = 1
$('.box').on('click',function(){
  if(flag==1){
    $(this).css('color','#000')
    flag =2;
  }
  if(flag==2){
    $(this).css('color','#cd0000')
    flag =1;
  }
})



事件對像


<style>
.jq-tb{

width:100%;border-collapse: collapse

}
.jq-tb td{border:1px solid #ccc;padding:5px;}
.jq-tb tr>td:first-child{min-width: 100px;

text-align: center;}

</style>

e.type 獲取事件的類型,如click;
e.target 綁定DOM元素,所以如改變是innerHTML
e.data 添加額外數據,可以是num,str,arr,obj
$('p').on('click',123, function (e) {
    console.log(e.data);  //123
})

</td>

</tr>
<tr>
    <td>e.relatedTarget</td>
    <td>获取移入到box之前的那个dom元素
$('.box').mouseover(function(e){
  alert(e.relatedTarget)
})

</td>

</tr>
<tr>
    <td>e.currentTarget</td>
    <td>绑定的DOM元素,相当于this,区别与e.target
$('.box').click(function(e){
  e.currentTarget //
})

</td>
</tr>

<tr>
    <td>e.e.pageX/Y</td>
    <td>页面原点,一拉动滚动条,则肯定比clientX大</td>
</tr>
<tr>
    <td>e.screenX/Y</td>
    <td>相对于屏幕的位置</td>
</tr>
<tr>
    <td>e.clientX/Y</td>
    <td>可視區xy,與滾動條無關 </td>
</tr>
<tr>
    <td>e.result</td>
    <td>同一元素绑定事件上一个的return返回值;</td>
</tr>
<tr>
    <td>e.timeStamp</td>
    <td>时间戳</td>
</tr>
<tr>
    <td>e.which</td>
    <td>1、如果使用鼠標,則左1中2右3;<br />2、使用按鍵觸發,則返回keyCode</td>
</tr>
<tr>
    <td>e.altKey/e.shifeKey/e.ctrlKey/e.metaKey</td>
    <td>是否按下,true false</td>
</tr>

方法:

e.preventDefault() 取消默認行為
e.isDefaultPrevented() 是否調用e.preventDefault()方法
e.stopPropagation() 取消冒泡
e.isPropagationStopped() 是否調用e.stopPropagation()方法
e.stopImmediatePropagation() 取消事件冒泡,并取消事件的后续处理函数
$('.box').click(function (e) {
    e.stopImmediatePropagation()  //调用取消冒泡,
})
$('.box').click(function (e) {
alert(123)                        //并且这里也不会执行
})

</td>
</tr>
<tr>

<td>e.isImmediatePropagationStopped()</td>

<td>判断是否调用了...方法 </td>
</tr>
</table>



高級事件


模拟点击

//注意与bind获取额外数据的区别:
$('#inp').click(function () {
    alert(123)
}).trigger('click')   //.click() 简写

//trigger额外数据只有一条时可省[],多条不能省略,第二条之后无法识别

$('#inp').click(function (e,data1,data2,data3) {
    alert(data1+data2+data3[1])
}).trigger('click',['123','abc',['j','k','l']])


$('p').on('click',123, function (e) {
    console.log(e.data);  //123
})

自定义事义事件,主要给trigger使用,本身自已无法执行

$('#inp').bind('mye', function () {
    alert('自定义可件')
}).trigger('mye')

triggerHandler() 相比 trigger; 有四點不同


1、触发事件但不会执行事件的默认行为;
即相当于模拟:

$('form').submit(function (e) {
    e.preventDefault()
}).trigger('submit')

2、如是$('多个input').只会执行匹配到的第一个,而trigger会执行所有匹配到的

3、返加值,trigger为jq对象,所以可以连写

alert($('#inp').bind('mye', function () {
    alert('自定义可件')
}).trigger('mye')).css('color','red')

而triggerHandler返回值为return值或undefined; 所以无法连写

4、trigger会冒泡,triggerHandler不冒泡

$('input').bind('click.a', function () {
    alert('abc')
})

$('input').bind('click.x', function () {
alert('xyz')
})

$('input').bind('mouseover.a', function () {
alert('abc')
})

$('input').unbind('.a') //即可移除click.a mouseover.a
//当然,对于trigger,trigger('.a')也一样执行两个


事件委託
live(),可以动态绑定,因为live事件是document事件;而点击btn其它是冒泡到document上,并且点击document时需要验证e.type e.target才能触发 ;

(1.4.3jq已淘汰:冒泡传得太长,且不支持连写调用)

$('.btn').live('click', function () {
    $(this).clone().appendTo('#b')
})

//相对的,取消为
$('.btn').die('click')

live的替换方法'父元素'.delegate(‘动作’,‘点击元素’,函数) ; 1.7版本已淘汰,整合到on

$('#b').delegate('click', '.btn',function () {
    $(this).clone().appendTo('#b')
})
//相对的,取消为
$('.btn').undelegate('click')

推荐使用整合:on('动作','点击元素',function)

$('#b').on('click.a','.btn', function () {
    $(this).clone().appendTo('#b')
})

$('#b').off('click.a')

//one只執行一次即取消
$('#b').one('click.a','.btn', function () {
    $(this).clone().appendTo('#b')
})



jq中返回的this是原生的,所以可以這麼寫

var _box = $('.box')
_box.click(function(){
    alert(this.innerHTML);
})
//alert($('input').val()); //获取
//$('input').val('7777'); //针对多个input的value值进行设置
alert($('input').val()); // 针对集合进行获取操作,只获取第一个

[=]
1
[$=]
[*=]

$('li').slice(1,4).css('background','red') //選中的是2,3,4;slice(1,2)什麼都選不中,slice(1,2),選中的是2

closest():找指定的一个最近的祖先元素(包括自身)(该函数必须加参数);它只能选择到一个唯一的元素

// 【指定的节点 == 前面部份 $('ul')  元素 == 被操作部分】

//append():把元素添加到指定的节点的里面的最后
var $li = $('<li>hello</li>');
// $('ul').append($li);

//prepend():把元素添加到指定的节点的里面的最前面  
// $('ul').prepend($li);

//before():把元素添加到指定的节点的前面
// $('ul').before($li);

//after():把元素添加到指定的节点的后面
$('ul').after($li);

appendTo()、prependTo()、insertBefore()、insertAfter(),指定節點與被操作部分對換,即指定要操作的節點放前,目標節點放後;
index():索引值,代表的就是当前元素在所有兄弟节点中排第几。如果不添加参数,索引值与标签类型是无关的。


  1. =

零JQ筆記 | 備忘 5-10

全选:当点击或勾选全部时,列表包括本身复选框选中;
全不选:当点击不选时,包括不选框、全选框都为未选中;
反选:注意全选框状态,需要each()所有,每个都设置一次;
allchk()检测全选框选中状态还是未选中,先算checkbox个数,each每个框,如果true则临时变量+1,最后,临时变量==checkbox个数,证明为全选,!=证明全选框应为未选中状态;

* attr可能返回disabled 或 disabled = 'disabled'
* prop()只返回标准的true false
* 1/只添加属性名称即生效应该使用prop()
* 2/只存在true/flase应该使用prop()
* 所以操作checkbox 的状态时建议全部使用prop()

<pre> //全选

$(&#39;#CheckedAll&#39;).click(function () {
    if (this.checked) {
        $(&#39;[name=items]:checkbox&#39;).prop(&#39;checked&#39;, true)
    } else {
        $(&#39;[name=items]:checkbox&#39;).prop(&#39;checked&#39;, false)
    }
    allchk() //设置全选框状态
})
//全不选
$(&#39;#CheckedNo&#39;).click(function () {
    $(&#39;[name=items]:checkbox,#CheckedAll&#39;).prop(&#39;checked&#39;, false)
    allchk()
})
//反选
$(&#39;#CheckedRev&#39;).click(function () {
    $(&#39;[name=items]:checkbox&#39;).each(function () {
        $(this).prop(&#39;checked&#39;, !$(this).prop(&#39;checked&#39;))
        //this.checked = !this.checked
    })
    allchk()
})
$(&#39;[name=items]:checkbox&#39;).click(function () {
    allchk()
})
$(&#39;#print&#39;).click(function () {
    var arrv = [
    ]
    $(&#39;[name=items]:checkbox:checked&#39;).each(function (i) {
        arrv[i] = $(this).val()
        //arrv.push( $(this).val())
    })
})
//检测及设置全选框是否选中
function allchk() {
    var _chkn = $(&#39;[name=items]:checkbox&#39;).size()
    var _chk = 0
    $(&#39;[name=items]:checkbox&#39;).each(function () {
        if ($(this).prop(&#39;checked&#39;)) {
            _chk++
        }
    })
    if (_chkn == _chk) { //全选
        $(&#39;#CheckedAll&#39;).prop(&#39;checked&#39;, true)
    }
    else {//不全选
        $(&#39;#CheckedAll&#39;).prop(&#39;checked&#39;, false)
    }

See the Pen jbyXro by elmok (@elmok) on CodePen.


<script async src="//assets.codepen.io/assets/embed/ei.js"></script>


select multiple 事件,$('select:first-child option:selected') 获取被选中,

然后使用appendTo【剪切】添加;

使用dblclick()双击事件,重点:获取当前选项:$('option:selected',this);


$('') 完整=== $('',document),后面是作用域;

console.log($('select:first-child option:eq(2)').val());获取第2个值

console.log($('select:first-child option:eq(2)').text());获取第2个text值

<select name="" id="" multiple="multiple">
    <option value="1">选项1</option>
    <option value="2">选项2</option>
    <option value="3">选项3</option>
    <option value="4">选项4</option>
    <option value="5">选项5</option>
</select>

<select name="" id="" multiple="multiple"></select>
<div class="add">选中添加到左边</div>
<div class="addall">全部添加到右边</div>
<script src="jquery-1.11.1.js"></script>
<script>
    $('.add').click(function () {
        var _options = $('select:first-child option:selected')
        _options.appendTo('select:nth-of-type(2)')
    })
    $('.addall').click(function () {
        var _options = $('select:first-child option')
        _options.appendTo('select:nth-of-type(2)')
    })
    //绑定事件,通过$('option:selected',this) 方法获取被选中选项,
    $('select:first-child').dblclick(function () {
        var _options = $('option:selected', this)
        _options.appendTo('select:nth-of-type(2)')
    })
</script>




1、先添加提示内容;

2、文本框失去焦点后处理;

3、由于每次失去焦点后都会创建一个新元素,所以创建之前先删除以前的 remove();

4、在提交表单之前,需要对表单整体进行一次验证,使用trigger()触发blur;

5、即时提醒,表单元素绑定keyup和focus事件;

6、trigger('blur')不仅会触发元素绑定的blur事件,也会触发默认,所以使用triggerHandler('blur'),不触发默认事件

See the Pen meRvbv by elmok (@elmok) on CodePen.


<script async src="//assets.codepen.io/assets/embed/ei.js"></script>

100%死记硬背:对于高版本jq.1.7+ checked, selected 这些属性要用 prop()来操作

例如單選radio控制表格單高亮,当前tr加click,$(this).addClass('on').【兄弟去掉】.siblings().removeClass('on').【返回tr $(this)】.end().【找radio】.find(':radio').【加属性】.prop('checked',true)
,使用attr会出错

<style>
    table{border-collapse: collapse}
    td{border:1px solid #cccccc; padding: 5px 20px;}
    .on{ background: #f1f1f1;}
</style>
<table>
    <tbody>
    <tr>
        <td><input type="radio" name="item" id=""/></td>
        <td>a</td>
        <td>a</td>
        <td>a</td>
    </tr>
    <tr>
        <td><input type="radio" name="item" id=""/></td>
        <td>a</td>
        <td>a</td>
        <td>a</td>
    </tr>
    </tbody>
</table>
<script src="jquery-1.11.1.js"></script>
<script>
$('table tr').click(function () {
    $(this).addClass('on')
            .siblings().removeClass('on')
            .end().find(':radio').prop('checked',true)

})
</script>

//当然也可以使用
$('table :radio:checked').parent().parent().addClass('on')
$('table :radio:checked').parents('tr').addClass('om')
$('tbody>tr:has(:checked)').addClass('on')

表格多行高亮:

$('table tr').click(function () {
  if ($('table tr').hasClass('on')) {
    $(this).removeClass('on').find(':checkbox').prop('checked', false)
  } else {
    $(this).addClass('on').find(':checkbox').prop('checked', true)
  }

//當然,更高級點的寫法
$('table tr').click(function () {
  var hasCheck = $(this).hasClass('on')
  $(this) [hasCheck ? 'removeClass' : 'addClass']('on').find(':checkbox').prop('checked', !hasCheck)
})

表格收縮

<tr class="parent" id="row_01"><td colspan="3">前台设计组</td></tr>
<tr class="child_row_01"><td>张山</td><td>男</td><td>浙江宁波</td></tr>
<tr class="child_row_01"><td>李四</td><td>女</td><td>浙江杭州</td></tr>
   $('table tr.parent').click(function () {
        $(this).toggleClass('on')
                .siblings('.child_'+this.id).slideToggle('slow')
    })


零JQ筆記 | 備忘1-4

mouseenter 與 mouseover

條件:目標點為外層元素,mouseenter在內層裏移到子元素不會觸發,只有從別的元素移到目標點才會觸發;mouseover在內層移到任意子元素都會觸發;
原理:mouseenter 無冒泡機制,mouseover有冒泡機制

<style>
div{ width: 200px;}
.box,.box2{ background: #727272; color: #ffffff;}
.div,.div2{border:1px solid #cccccc;padding:15px;}
</style>
<div class="div">
<div class="box">0</div>
</div>
<div class="div2">
<div class="box2">0</div>
</div>
<script>
var i = 1;
var j = 1;
$('.div').mouseenter(function () {
    $('.box').html(i++)
})
$('.div2').mouseover(function () {
    $('.box2').html(j++)
})
</script>

mouseleave 與 mouseout 類似

hover方法用的是: mouseenter mouseleave方法,so,當需觸發hover方法第2個fn時,使用trigger('mouseleave');



事件對象:
1)e.type,獲取事件的類型:

$('#a').click(function (e) {
    e.preventDefault()
    console.log(e.type); // click
})

2)e.target 獲取觸發事件的元素;

$('#a').click(function (e) {
    e.preventDefault()
    console.log(e.target); 
//<a href="http://baidu.com" id="a">aaa</a>
})

3)e.relatedTarget
標準DOM發生元素可通過e.target訪問,相關元素通過e.relatedTarget訪問


对于"mouseenter"、"mouseover"等事件而言,relatedTarget属性返回被离开的DOM元素。

对于"mouseout"、"mouseleave"事件而言,relatedTarget属性返回被进入的DOM元素。

对于"focus"事件而言,relatedTarget属性返回失去焦点的DOM元素(如果有的话)。

对于"blur"事件而言,relatedTarget属性返回获得焦点的DOM元素(如果有的话)。

如果当前事件没有涉及到其他元素,则返回null或undefined(视情况而定)。

<script src="jquery-1.11.1.js"></script>
<style>
*{ margin: 0; padding: 0;}
.wrap{padding:10px;border:1px solid #ccc;}
.box,p{padding:20px;border:1px solid #ccc;}
</style>
<div class="wrap" id="wrap">
    wrap,父元素 id=wrap
    <div class="box" id="box">box相臨元素 id=box</div>
    <a href="#">綁定事件點a</a>
    <p id="p">p相臨元素 id=p</p>
</div>
<script>
$('a').bind('mouseout', function (e) {
console.log(e.relatedTarget.id);//離開a後到哪個元素即哪個元素
})
</script>

4)e.which
鼠標左中右及鍵盤鍵值

$('a').mousedown(function (e) {
    console.log(e.which);
})
$('a').keyup(function (e) { //获取键盘的按钮值
    console.log(e.which)
})
$('a').keyup(function (e) {
    console.log(e.metaKey); //按ctrl
})



1、事件綁定移除
bind、unbind、one、on、off、delegate、undelegate
2、常用模擬
trigger(type,[data]);可傳參;

$('.a').bind('myClick', function (elem,n1,n2) {
    alert(n1+n2)
})
$('.a').trigger('myClick',[2,3])

下面方法自動觸發input元素綁定focus事件,也會使焦點本身得到,瀏覽器默認行為,如有多個input元素,則觸發最後一個;

$('input').trigger('focus')

$('input').triggerHandler('focus')
//只觸發focus事件,焦點不會得到,即同時會取消瀏覽器對此事件的默認行為

3、命名空间

$('.box').bind('click',function(){
    console.log('default')
})
$('.box').bind('click.fn1',function(){
    console.log('fn1')
})
$('button').click(function(){
    $('.box').trigger('click!') //加!表示匹配所有不包命名空间的click,即fn1不会被执行;
})

4、动画
1个animate,同步执行,走斜线

$(this).animate({'left','200px','top','200px'})

2个animate,先后执行,走直角

$(this).animate({'left','200px'})
        .animate({'top','200px'})

若最后一切,切换css样式,而不是隐藏元素,则需要回调函数

$('.box').on('click', function () {
    $(this).animate({
        left:'500',height:'200',opacity:1
    },2000)
    .animate({
       top:'200px',width:'200'
    },2000).css('border','5px solid blue') 
    //最后一步css(),但这里动画一开始便会被执行,
    //若想动画结束后再执行,使用回调
})

$('.box').on('click', function () {
    $(this).animate({
        left:'500',height:'200',opacity:1
    },2000)
            .animate({
                top:'200px',width:'200'
            },2000, function () {
                $(this).css('border','5px solid blue')
            })
})
$('#btn').on('click', function () {
   $('.box').slideDown('normal', function () {
       $(this).css('border','5px solid blue')
       console.log($(this));
   })
})


一、停止元素动画

stop(clearQueue)

clearQueue,gotoEnd,true或false,

clearQueue: 代表是否要清空未扫行完的动画队列

gotoEnd: 代表是否直接将正在执行的动画跳转到末状态

stop(),立即停止当前正在进行,如下面还有动画则继续执行;

鼠标快速移动:

$('#btn').hover(function () {
    $('.box').stop().slideDown()
}, function () {
    $('.box').stop().slideUp()
})

stop(true),当前元素接下来尚未执行完的动画队列清空;

$('.box').hover(function () {
    $(this).stop()
            .animate({  //只带一个参数只能处理到这里
                height:150
            },200)
            .animate({  //处理这里需要stop(true)
                width:300
            },300)
}, function () {
    $(this).stop()
            .animate({
                height:22
            },200)
            .animate({
                width:60
            },300)
})

gotoEnd用于让正在执行的动画直接到达结束时刻的状态,通常用于后一个动画需要基于前一个动画的末状态况,可使用stop(false,true)

stop(true,true),停止当前动画并直接到达当前动画末状态,并清空队列。

jq只能设置正在执行动画的最终状态,没提供直接到达【未执行动画】队列的方法,以下无论怎么设置都无法在改变width或height时,将此div末状态变成300 x 150,且opacity:2

$('.box').on('mouseover', function () {
    $('.box').animate({
        width:300
    })       .animate({
                height:180
            })
            .animate({
                opacity:0.2
            })
})

二、判断元素是否处于动画状态

if(!$(elem).is(':animated')){
    //如果当前没有进行动画
}
<div id="box" style="width: 100px; height: 100px; background: #f00; position: absolute;"></div>
<script src="jquery1.11.1.js"></script>
<script>
    $(function() {
        // 开始动画
        $("#box").animate({left: 500}, 5000);
        $(document).on("click", function() {
            // 在选择器中使用
            if($("#box:animated").length) {
                $("body").append("<p>#box 尚在动画</p>");
            }

            // 在 is 中使用
            if(!$("#box").is(":animated")) {
                $("body").append("<p>#box 动画停止</p>");
            }
        });
    });
</script>

animate()方法替代:

//show()
$('.box').animate({
    height:'show',width:'show',opacity:'show'
},400)

//fadeIn(400)
$('.box').animate({
   opacity:'show'
},400)

//slideDown()
$('.box').animate({
   height:'show'
},400)

延迟动画:

$(this).animate({
    left:400
}).delay(1000)
    .animate({
    width:'200px'
})

1)1组元素动画:当在一个animate()应该多个时,动画是同时发生,以链式写法应用动画时,按顺序发生;
2)多组元素:默认情况下,动画同时发生,当以回调应用时,按回调顺序发生
非动画队列也按顺序,需要写在回调里


简单图片切换:

<div class="v-show clearfix">
    <div class="v-caption clearfix">
        <h4>图片</h4>
        <div class="v-caption-tip">
            <span class="on">1</span>
            <span>2</span>
            <span>3</span>
        </div>
        <div class="v-caption-btn">
            <span class="prev">上一页</span>
            <span class="next">下一页</span>
        </div>
        <em><a href="#">更多</a></em>
    </div>
    <div class="v-content">
        <ul class="ul-pic">
            <li><img src="1.jpg" alt=""/></li>
            <li><img src="2.jpg" alt=""/></li>
            <li><img src="3.jpg" alt=""/></li>
            <li><img src="1.jpg" alt=""/></li>
            <li><img src="2.jpg" alt=""/></li>
            <li><img src="3.jpg" alt=""/></li>
            <li><img src="2.jpg" alt=""/></li>
            <li><img src="3.jpg" alt=""/></li>
        </ul>
    </div>
</div>

1、要点击的项为.next .prev,所以可以此点为基点向上找元素;
2、每次切换的宽度为ul父级的宽度即可;
3、page代表第一板,每板有3个图片,即总板数为li个数/3,向上取整;
4、!_show.is(':animated')限制在非运动时点击才生效;
5、-=,+=表示每次点击都累加或累减;

var _parent = $('.v-caption-btn span').parents('div.v-show');
var _show = _parent.find('.ul-pic');
var _content = _parent.find('div.v-content');
var v_width = _content.width();
var len = _show.find('li').length;
var page = 1;
var i = 3;
var page_count = Math.ceil(len / i);
$('.next').on('click', function () {
  if (!_show.is(':animated')) {
    if (page == page_count) {
      _show.animate({
        left: 0
      }, 'normal');
      page = 1;
    } 
    else {
      _show.animate({
        left: '-=' + v_width  //注意:-=
      }, 'slow');
      page++;
    }
    _parent.find('span').eq((page - 1)).addClass('on').siblings().removeClass()
  }
})
$('.prev').on('click', function () {
  if (!_show.is(':animated')) {
    if (page == 1) {  //第一板切换到最后一板
      _show.animate({
        left: '-=' + v_width * (page_count - 1)
      }, 'slow');
      page = page_count
    } 
    else {
      _show.animate({
        left: '+=' + v_width  //注意:+-
      }, 'slow');
      page--;
    }
    _parent.find('span').eq((page - 1)).addClass('on').siblings().removeClass()
  }
})

css主要设置ul父级relative,ul为absolute;

.v-content{overflow:hidden;position:relative}
.v-show{position:absolute}

*{margin:0;padding:0;font-size:16px}ul{float:left}.ul-pic{position:relative}img{width:150px;vertical-align:top}li{list-style:none;float:left;margin:10px;border:1px solid #ccc;padding:1px}.v-show{width:524px;margin:0 auto;border:1px solid #ccc;}.ul-pic{width:2000px}.v-caption-btn,.v-caption-tip,h4{float:left;margin-right:20px}.v-caption em{float:right}.on{color:red}.clearfix:after{content:'';width:0;height:0;display:block;clear:both;visibility:hidden}
© 2025 J.chongj.chong@qq.com 模板由cho制作.