Skip to content

Instantly share code, notes, and snippets.

@wcc526
Created September 26, 2015 12:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wcc526/6fa7d49338e79ae5c267 to your computer and use it in GitHub Desktop.
Save wcc526/6fa7d49338e79ae5c267 to your computer and use it in GitHub Desktop.
javascript workflow

Debug

  • console.log('Hello');
  • console.debug('debug');
  • console.info('info');
  • console.warn('warn');
  • console.error('error');

Time

window.onload = function(){
    console.time('myTimer');
    complexFunction();
    console.timEnd('myTimer');
}

匿名立即执行函数

好处是保持变量为local

(function(){

})();

click function

(function(){
    $('button').click(function(){
        // 注意只有 jquery 才有 text 方法
        $(this).text('changed');

        // 判断变量
        var stylesheet = $(this).text().toLowerCase();
        console.log(stylesheet);
        $('link').attr('href',stylesheet+'.css');
    });
})();

data

<button data-file='day'> Day </button>
<button data-file='night'> Night </button>
(function(){
    $('button').click(function(){
        var stylesheet = $(this).data('file');
        console.log(stylesheet);
        $('link').attr('href',stylesheet+'.css');
    });
})();

使用缓存

(function(){
    var link = $('link');
    $('button').click(function(){
        // 用 $ 开头表示是 jquery 对象
        var $this = $(this);
        var stylesheet = $this.data('file');

        // siblings 表示兄弟对象
        $this.siblings('button').removeAttr('disabled');

        link.attr('href',stylesheet + '.css';
        $this.attr('disabled','disabled');

        // 使用 end 回到原先对象
        $this
            .siblings('button')
                .removeAttr('disabled')
                .end()
                .attr('disabled','disabled');
    });
})();

指定 target

(function(){
    $('dl').on('mouseenter','dt',function(){
        $(this)
            .next()
                .slideDown(200)
                .siblings('dd')
                    .slideUp(200);
    });
})();

clone 方法

(function(){
    $('h2').bind('click',function(){
        console.log('clicked');
        // 参数为true,复制事件处理函数
        $(this).clone(true).appendTo('body');
    });
})();

appendTo

(function(){
    $('<h2></h2>',{
        text: 'Hello from Javascript',
        class: 'myClass'
    }).appendTo('article');
})();

proxy

用来保持上下文

var obj = {
    doIt: function(e){
        console.log(this);
        e.preventDefault();
    }
}
$('a').on('click',$.proxy(obj.doIt,obj));

查看变量类型

var something = parseInt( box.css('font-size'),10);
console.log(typeof something);

直接使用引用

(function(){
    var box = $('div.box');
    $('button').on('click',function(){
        box.css({
            'font-size': '+=5',
            'color': 'white',
        });

        // 动画效果
        box.animate({
            'fontSize': '+=5'
        },{
            duration: 500,
            complete: function() {
                console.log('completed');
            },
            step: function() {
                console.log('step here');
            }
        });
    });
})();

查看内容

var slider = new Slider();
console.dir(slider);

使用类

function Slider(container,nav){
    this.container = container;
    this.nav = nav;
    this.imgs = this.container.find('img');
    this.imgWidth = this.imgs[0].width;
    this.imgsLen = this.imgs.length;
    this.current = 0;
}
Slider.prototype.traansition = function(coords){
    this.container.animate({
        'margin-left': coords || -( this.current * this.imgWidth )
    });
};
Slider.prototype.setCoordinates = function( dir ){
    // 使用位运算简化代码
    var pos = this.current;
    pos += ~~( dir == 'next' ) || -1;
    this.current = ( pos < 0)? this.imgsLen - 1 : pos % this.imgsLen;
    return pos;
};

getJSON

(function(){
    var Twitter = {
        init: function() {
            this.url = 'http://search.twitter.com/search.json?q=abc&callback=?';
            this.fetch();
        },
        fetch: function() {
            $.getJSON(this.url,function(data){
                this.tweets = $.map(data.results,function(tweet){
                    return {
                        author: tweet.from_user,
                        tweet: tweet.text,
                        thumb: tweet.profile_image_url,
                        url: 'http://twitter.com/'+tweet.from_user+'/status/'+tweet.id_str
                    };
                });
            });
        }
    };
    Twitter.init();
})();

grep 方法

(function(){
    var arr = [1,2,3,4,5,6,7,8,9];
    arr = $.grep( arr, function( val, index ){
    // 返回值大于 5 的元素
        return val > 5;
    }, true );
    console.log(arr);
})();

利用事件传递异步返回的消息

$.getJSON('http://search.twitter.com/search.json?q=dogs&callback=?',function(results){
    $(document).trigger('twitter/results',results);
});
$(docment).on('twitter/results',function(e,results){
    console.log(results);
});

初始化 jQuery 对象

在页面 DOM 加载完成后(不包括图片下载完成)执行你所需要的代码

(function( $ ) {
}) ( jQuery );

导入其它 html 的内容

$('a').on('click',function(e){
  $('body').load('about.html .container');
  e.preventDeafult();
});

ajax post

$.post('load.php',function(data){
    if(data){
        $('#content').val(data);
    }
});
$('form').on('submit',function(e){
    $.post('save.php',$(this).serialize(),function(response) {
        alert( response );
    });
    e.preventDefault();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment