Javascript相關紀錄

摘要:Javascript相關紀錄


紀錄一些常用到JS都歸納在此篇


Javascript's iif 用法
======================
alert((1 == 1 ? 'Y' : 'N'))

 

Javascript cookie的讀取
=================================================================
       function getCookie(c_name) {
            if (document.cookie.length > 0) {                
                var c_list = document.cookie.split("\;");
                for (i in c_list) {                
                    var cook = c_list[i].split("=");
                    if (cook[0] == c_name) {                       
                        return unescape(cook[1]);
                        document.write(unescape(cook[1]));                        
                    }
                }
            }
            return null
        }


        function setCookie(c_name, value, expiredays)   // c_name: cookie name, value: cookie value, expiredays: cookie 有效天數 
        {
            var exdate = new Date()                        // 宣告 exdate
            exdate.setDate(exdate.getDate() + expiredays)  // 將 exdate 設成今天加上過期天數
            document.cookie = c_name + "=" + escape(value) +  // 產生 cookie 內容  c_name=escape(value);expires=exdate
            ((expiredays == null) ? "" : ";expires=" + exdate)
        }

Javascript's replace 用法
==============================
res = str.replace("Microsoft", "W3Schools"); 

 

Replace字串中所有需要置換的字(之前的只能Replace第一筆)
=========================================
"123''456''789".replace(/''/g, "");

output:123456789

Javascript's 抓網址參數
======================
​
function request(name) {

var AllParams = window.location.search.substring(1);

var Params = AllParams.split("&");

for (i = 0; i < Params.length; i++) {

var Param = Params [i].split("=");

if (Param[0] == name) return Param[1];

}

return "";

}

 


Avoid alert msg in IE when we close window.(chrome沒有這個問題)
================================
function clolsewindow(){

                window.opener = null;
                window.open('','_self'); 
                window.close(); 
}

 


陣列小技巧
==============================
var fruit = [];
fruit.push('Strawberry');
fruit.push('Ginkgo');
       
//取代
//fruit[0] = 'Strawberry';
//fruit[1] = 'Ginkgo';

//用join可在索引之間插入字串(尾巴不會有)
document.write(fruit.join(';'))  //Strawberry;Ginkgo

 

var GenerateUrl = '點我';

document.write(GenerateUrl.link('www.google.com'));

//<a href='www.google.com'>點我</a>