分享javascript、jquery實用程式碼片段,javascriptjquery
本文執行個體為大家簡單分享javascript、jquery實用demo,供大家參考,具體內容如下
javascript判斷H5頁面離開
function onbeforeunloadFn(){ console.log('離開頁面'); //...code}function showOnbeforeunload(flags){ if(flags){ document.body.onbeforeunload = onbeforeunloadFn; }else{ document.body.onbeforeunload = null; }}$(function(){ showOnbeforeunload(true);})
jq判斷img標籤圖片地址是否已經載入完畢
imgStatus = 0; $("img").each(function(){ if(this.complete){/*this.complete代表圖片載入完成*/ imgStatus++; } });
iframe擷取內容-和設定
if($(".ad_show iframe").size() > 0 ){ $(".ad_show iframe").attr("id","iframead");/*設定iframe的id*/ /*擷取id為iframead的iframe的dom對象*/ var iframebox = document.getElementById("iframead").contentWindow; /*設定兜底內容*/ iframebox.document.body.innerText = "1234";}
javascript擷取瀏覽器上一頁的url
/*返回上一次url,如果是新視窗則不能擷取到*/var beforeUrl = document.referrer;
關於頭疼的移動端點擊冒泡事件
<script>$(".class").live('tap',function(oEvent){ e = window.event || oEvent; if(e.stopPropagation){ e.stopPropagation(); }else{ e.cancelBubble = true; } e.preventDefault();});</script>/*雖說tap事件可以阻止大部分冒泡事件,但是還是有一小部分移動端不吃你這套,那麼有另外一個解決辦法*//*將層級間的事件通過H5屬性data-flag="true"來控制*/<!--html--><div class="parentTap" data-flag="true"> <div class="childTap" data-flag="false"> <div class="childsTap" data-flag="false"> .... </div> </div></div><!--給父級parentTap綁定一個點擊事件--><!--給子級childTap綁定一個點擊事件--><!--給子孫級childsTap綁定一個點擊事件--><script type="text/javascript"> var bindInit = function(className){ if($(className).size() > 0){ $(className).on('tap',function(oEvent){ e = window.event || oEvent;if(e.stopPropagation){e.stopPropagation();}else{e.cancelBubble = true;}e.preventDefault(); var flag = $(this).data('flag'); if(flag){/*為true時允許點擊進入事件*/ /* code... */ } }); } } $(function(){ bindInit('.parentTap'); bindInit('.childTap'); bindInit('.childsTap'); });</script>
簡單倒計時功能
<div class="newTime" data-end="2016-10-13 23:59:59" data-now="2016-10-13 03:59:59"> <div class="t_d"></div> <div class="t_h"></div> <div class="t_m"></div> <div class="t_s"></div></div> <script type="text/javascript"> /*倒計時*/ var timeDown = { GetRTime: function (timeId,oldNowTime) { var tempTime;/*儲存上一次時間*/ if(oldNowTime){ tempTime = new Date(oldNowTime.getTime() + 1000);/*如果有上一次時間則賦值*/ /*console.log(tempTime);*/ } var EndTime = new Date($("#" + timeId).data("end"));/*擷取結束時間*/ if (!tempTime) { if ($("#" + timeId).data("now") == "" || $("#" + timeId).data("now") == "null") { var NowTime = new Date(); } else { var NowTime = new Date($("#" + timeId).data("now"));/*取開始時間*/ } } else { var NowTime = tempTime; } if (EndTime.getTime() >= NowTime.getTime()) {/*判斷時間*/ var t = EndTime.getTime() - NowTime.getTime();/*得到結束時間減去開始時間的時間戳記*/ var d = Math.floor(t / 1000 / 60 / 60 / 24);/*日*/ var h = Math.floor(t / 1000 / 60 / 60 % 24);/*時*/ var m = Math.floor(t / 1000 / 60 % 60);/*分*/ var s = Math.floor(t / 1000 % 60);/*秒*/ /*將時間填入對應的html中*/ $(".t_d", "#" + timeId).html((d > 9 ? '' : '0') + d); $(".t_h", "#" + timeId).html((h > 9 ? '' : '0') + h); $(".t_m", "#" + timeId).html((m > 9 ? '' : '0') + m); $(".t_s", "#" + timeId).html((s > 9 ? '' : '0') + s); tempTime = new Date(NowTime.getTime() + 1000);/*將開始時間+1秒*/ setTimeout(function () { timeDown.GetRTime(timeId,NowTime);/*等待一秒後繼續執行*/ }, 1000); } else if (EndTime.getTime() == NowTime.getTime()) {/*當時間相等時要做處理的code*/ $("#"+timeId).hide(); } } } var t=0; if ($(".newTime").size() > 0) { $(".newTime").each(function(){ var timeId="timeOut"+t; $(this).attr("id",timeId);/*設定多個倒計時時指定唯一id*/ t++; timeDown.GetRTime(timeId,null);/*開始調用*/ }); } </script>
jQuery的節點操作
jQuery.parent(expr) /*找父親節點,可以傳入expr進行過濾,比如$("span").parent()或者$("span").parent(".class")*/jQuery.parents(expr) /*類似於jQuery.parents(expr),但是是尋找所有祖先元素,不限於父元素*/jQuery.children(expr) /*返回所有子節點,這個方法只會返回直接的孩子節點,不會返回所有的子孫節點*/jQuery.contents() /*返回下面的所有內容,包括節點和文本。這個方法和children()的區別就在於,包括空白文本,也會被作為一個*//* jQuery對象返回,children()則只會返回節點 jQuery.prev(),返回上一個兄弟節點,不是所有的兄弟節點 jQuery.prevAll(),返回所有之前的兄弟節點 jQuery.next(),返回下一個兄弟節點,不是所有的兄弟節點 jQuery.nextAll(),返回所有之後的兄弟節點 jQuery.siblings(),返回兄弟姐妹節點,不分前後 jQuery.find(expr),跟jQuery.filter(expr)完全不一樣。 jQuery.filter()是從初始的jQuery對象集合中篩選出一部分, 而jQuery.find()的返回結果,不會有初始集合中的內容, 比如$("p"),find("span"),是從<p>元素開始找<span>,等同於$("p span")*/
js中if判斷語句中的in文法
/*在js代碼中通常的if判斷語句會這樣寫:*/if(1 == 1){ alert("1等於1");}else{ alert("1不等於1");}/*而在in寫法下可以這樣:*/if(1 in window){ alert("window包含1");}else{ alert("window不包含1");}
js的try-catch
try{ foo.bar();}catch(e){ console.log(e.name + ":" + e.message);}try{ throw new Error("Whoops!");}catch(e){ console.log(e.name + ":" + e.message);} /*改js代碼會捕獲一個異常錯誤: 因為foo.bar();是未定義的; 因此在js代碼中如果沒有異常捕獲,整個頁面都不會繼續解析. 從而導致頁面載入失敗. 這裡就需要通過try-catch來異常捕獲這種錯誤,並把他反饋出來目前我們可能得到的系統異常主要包含以下6種: EvalError: raised when an error occurs executing code in eval() 翻譯:當一個錯誤發生在eval()執行代碼 RangeError: raised when a numeric variable or parameter is outside of its valid range 翻譯:當一個數值變數或參數的有效範圍之外 ReferenceError: raised when de-referencing an invalid reference 翻譯:引用無效的引用 SyntaxError: raised when a syntax error occurs while parsing code in eval() 翻譯:語法錯誤,當發生語法錯誤在eval()解析代碼裡 TypeError: raised when a variable or parameter is not a valid type 翻譯:錯誤類型:當一個變數或參數不是一個有效類型 URIError: raised when encodeURI() or decodeURI() are passed invalid parameters 翻譯:調用encodeURI()或decodeURI()時,傳入的參數是不通過無效的以下是異常捕獲是的屬性: Error具有下面一些主要屬性: description: 錯誤描述 (僅IE可用). fileName: 出錯的檔案名稱 (僅Mozilla可用). lineNumber: 出錯的行數 (僅Mozilla可用). message: 錯誤資訊 (在IE下同description) name: 錯誤類型. number: 錯誤碼 (僅IE可用). stack: 像Java中的Stack Trace一樣的錯誤堆棧資訊 (僅Mozilla可用).*/ /* 如要判斷異常資訊的類型,可在catch中進行判斷: */try { coo.bar();//捕獲異常,ReferenceError:引用無效的引用}catch(e){ console.log(e instanceof EvalError); console.log(e instanceof RangeError); if(e instanceof EvalError){ console.log(e.name + ":" + e.message); }else if(e instanceof RangeError){ console.log(e.name + ":" + e.message); }else if(e instanceof ReferenceError){ console.log(e.name + ":" + e.message); }}
js中typeof和instanceof區別
/*先捕獲異常,拋出異常*/try { throw new myBlur(); // 拋出當前對象 }catch(e){ console.log(typeof(e.a)); //返回function類型 if(e.a instanceof Function){//instanceof用於判斷一個變數是否某個對象的執行個體,true console.log("是一個function方法"); e.a();//執行這個方法,輸出"失去焦點" }else{ console.log("不是一個function方法"); }}function myBlur(){ this.a = function(){ console.log("失去焦點"); };}/* 通暢typeof一般只能返回如下幾個結果: number,boolean,string,function,object,undefined; 如果要用if做比較則比較後面要用雙引號引起來*/ if(typeof(param) == "object"){ alert("該參數等於object類型"); }else{ alert("該參數不等於object類型"); }/*又如:*/console.log(Object instanceof Object);//trueconsole.log(Function instanceof Function);//true console.log(Number instanceof Number);//falseconsole.log(String instanceof String);//falseconsole.log(Function instanceof Object);//trueconsole.log(Foo instanceof Function);//trueconsole.log(Foo instanceof Foo);//false
HTML5緩衝sessionStorage
sessionStorage.getItem(key)//擷取指定key本機存放區的值sessionStorage.setItem(key,value)//將value儲存到key欄位sessionStorage.removeItem(key)//刪除指定key本機存放區的值sessionStorage.length//sessionStorage的項目數/*sessionStorage與localStorage的異同: sessionStorage和localStorage就一個不同的地方, sessionStorage資料的儲存僅特定於某個會話中, 也就是說資料只保持到瀏覽器關閉,當瀏覽器關閉後重新開啟這個頁面時,之前的儲存已經被清除。 而localStorage是一個持久化的儲存,它並不局限於會話sessionStorage和localStorage的clear()函數的用於清空同源的本機存放區資料: 比如localStorage.clear(),它將刪除所有同源的本機存放區的localStorage資料, 而對於SessionStorage,它只清空當前會話儲存的資料。sessionStorage和localStorage具有相同的方法storage事件: 在儲存事件的處理函數中是不能取消這個儲存動作的。 儲存事件只是瀏覽器在資料變化發生之後給你的一個通知。 當setItem(),removeItem()或者clear() 方法被調用, 並且資料真的發生了改變時,storage事件就會被觸發。 注意這裡的的條件是資料真的發生了變化。也就是說, 如果當前的儲存地區是空的,你再去調用clear()是不會觸發事件的。 或者你通過setItem()來設定一個與現有值相同的值,事件也是不會觸發的。 當儲存地區發生改變時就會被觸發。*/
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。