显示标签为“javacript”的博文。显示所有博文
显示标签为“javacript”的博文。显示所有博文

2009/02/25

cookie读写类

JavaScript语言: cookie操作代码

smartclick_Cookie = {

    get: function(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = smartclick_Cookie.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    },
    set: function(key, value, ttl, path, domain, secure) {
        cookie = [key+'='+    encodeURIComponent(value),
                   'path='+    ((!path   || path=='')  ? '/' : path),
                   'domain='+  ((!domain || domain=='')?  window.location.hostname : domain)];
       
        if (ttl)         cookie.push( 'expires='+smartclick_Cookie.hoursToExpireDate(ttl));
        if (secure)      cookie.push('secure');
       
        return document.cookie = cookie.join('; ');
    },

    //@param integer    ttl        Time To Live (hours)
    hoursToExpireDate: function(ttl) {
        if (parseInt(ttl) == 'NaN' ) return '';
        else {
            now = new Date();
            now.setTime(now.getTime() + (parseInt(ttl) * 60 * 60 * 1000));
            return now.toGMTString();
        }
    },
    trim: function( text ) {
        return (text || "").replace( /^\s+|\s+$/g, "" );
    }
}

几点说明:
1.ttl生存期时间单位是小时。
2.get方法的原理是字符串匹配,对[key=]value的中括号部分进行匹配,优于使用正则进行匹配,正则如有特殊字符的情况会很麻烦。

2008/12/11

Javascript(Jquery)获取键盘事件的key值,兼容FF2/3,IE,opera

获取event,keyCode是件麻烦事情,浏览器之间不统一。下面代码兼容性好。


<script>
//监听keypress事件,执行键盘一些快捷操作
$(document).keypress(function(event){
   
    //获取事件对象 w3c模型/ie模型
    //var event = arguments[0] || window.event;
    //取得键盘码
    var key = event.keyCode || event.which || event.charCode;
   
    switch( key ) {           
        //a 添加分类
        case 97 :    go("AddProductLink");return;
           
        //p 商品管理
        case 112 :    go("ProductsManageLink");return;
           
        //c 分类管理
        case 99 :    go("CategoriesManageLink");return;
       
        //s 搜索框聚焦
        case 115 :    setTimeout(function(){$('input#searchText').focus();});return;
           
        default :    return;
    }
    return;
});
</script>


清除事件继续向上冒泡,如果不希望其父级DOM捕获到此事件。


//对于INPUT框需要阻止事件继续向上冒泡
$('input').keypress(function(event){event.cancelBubble ? (event.cancelBubble = ture) : event.stopPropagation();});