分享javascript、jquery實用代碼段
本文實例為大家簡單分享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標簽圖片地址是否已經(jīng)加載完畢
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);/*等待一秒后繼續(xù)執(zhí)行*/ }, 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的節(jié)點操作
jQuery.parent(expr) /*找父親節(jié)點,可以傳入expr進行過濾,比如$("span").parent()或者$("span").parent(".class")*/ jQuery.parents(expr) /*類似于jQuery.parents(expr),但是是查找所有祖先元素,不限于父元素*/ jQuery.children(expr) /*返回所有子節(jié)點,這個方法只會返回直接的孩子節(jié)點,不會返回所有的子孫節(jié)點*/ jQuery.contents() /*返回下面的所有內容,包括節(jié)點和文本。這個方法和children()的區(qū)別就在于,包括空白文本,也會被作為一個*/ /* jQuery對象返回,children()則只會返回節(jié)點 jQuery.prev(),返回上一個兄弟節(jié)點,不是所有的兄弟節(jié)點 jQuery.prevAll(),返回所有之前的兄弟節(jié)點 jQuery.next(),返回下一個兄弟節(jié)點,不是所有的兄弟節(jié)點 jQuery.nextAll(),返回所有之后的兄弟節(jié)點 jQuery.siblings(),返回兄弟姐妹節(jié)點,不分前后 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代碼中如果沒有異常捕獲,整個頁面都不會繼續(xù)解析. 從而導致頁面加載失敗. 這里就需要通過try-catch來異常捕獲這種錯誤,并把他反饋出來 目前我們可能得到的系統(tǒng)異常主要包含以下6種: EvalError: raised when an error occurs executing code in eval() 翻譯:當一個錯誤發(fā)生在eval()執(zhí)行代碼 RangeError: raised when a numeric variable or parameter is outside of its valid range 翻譯:當一個數(shù)值變量或參數(shù)的有效范圍之外 ReferenceError: raised when de-referencing an invalid reference 翻譯:引用無效的引用 SyntaxError: raised when a syntax error occurs while parsing code in eval() 翻譯:語法錯誤,當發(fā)生語法錯誤在eval()解析代碼里 TypeError: raised when a variable or parameter is not a valid type 翻譯:錯誤類型:當一個變量或參數(shù)不是一個有效的類型 URIError: raised when encodeURI() or decodeURI() are passed invalid parameters 翻譯:調用encodeURI()或decodeURI()時,傳入的參數(shù)是不通過無效的 以下是異常捕獲是的屬性: Error具有下面一些主要屬性: description: 錯誤描述 (僅IE可用). fileName: 出錯的文件名 (僅Mozilla可用). lineNumber: 出錯的行數(shù) (僅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區(qū)別
/*先捕獲異常,拋出異常*/ try { throw new myBlur(); // 拋出當前對象 }catch(e){ console.log(typeof(e.a)); //返回function類型 if(e.a instanceof Function){//instanceof用于判斷一個變量是否某個對象的實例,true console.log("是一個function方法"); e.a();//執(zhí)行這個方法,輸出"失去焦點" }else{ console.log("不是一個function方法"); } } function myBlur(){ this.a = function(){ console.log("失去焦點"); }; } /* 通暢typeof一般只能返回如下幾個結果: number,boolean,string,function,object,undefined; 如果要用if做比較則比較后面要用雙引號引起來 */ if(typeof(param) == "object"){ alert("該參數(shù)等于object類型"); }else{ alert("該參數(shù)不等于object類型"); } /*又如:*/ console.log(Object instanceof Object);//true console.log(Function instanceof Function);//true console.log(Number instanceof Number);//false console.log(String instanceof String);//false console.log(Function instanceof Object);//true console.log(Foo instanceof Function);//true console.log(Foo instanceof Foo);//false
HTML5緩存sessionStorage
sessionStorage.getItem(key)//獲取指定key本地存儲的值 sessionStorage.setItem(key,value)//將value存儲到key字段 sessionStorage.removeItem(key)//刪除指定key本地存儲的值 sessionStorage.length//sessionStorage的項目數(shù) /* sessionStorage與localStorage的異同: sessionStorage和localStorage就一個不同的地方, sessionStorage數(shù)據(jù)的存儲僅特定于某個會話中, 也就是說數(shù)據(jù)只保持到瀏覽器關閉,當瀏覽器關閉后重新打開這個頁面時,之前的存儲已經(jīng)被清除。 而localStorage是一個持久化的存儲,它并不局限于會話 sessionStorage和localStorage的clear()函數(shù)的用于清空同源的本地存儲數(shù)據(jù): 比如localStorage.clear(),它將刪除所有同源的本地存儲的localStorage數(shù)據(jù), 而對于SessionStorage,它只清空當前會話存儲的數(shù)據(jù)。 sessionStorage和localStorage具有相同的方法storage事件: 在存儲事件的處理函數(shù)中是不能取消這個存儲動作的。 存儲事件只是瀏覽器在數(shù)據(jù)變化發(fā)生之后給你的一個通知。 當setItem(),removeItem()或者clear() 方法被調用, 并且數(shù)據(jù)真的發(fā)生了改變時,storage事件就會被觸發(fā)。 注意這里的的條件是數(shù)據(jù)真的發(fā)生了變化。也就是說, 如果當前的存儲區(qū)域是空的,你再去調用clear()是不會觸發(fā)事件的。 或者你通過setItem()來設置一個與現(xiàn)有值相同的值,事件也是不會觸發(fā)的。 當存儲區(qū)域發(fā)生改變時就會被觸發(fā)。 */
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
詳細聊聊TypeScript中unknown與any的區(qū)別
unknown類型比較謙虛,就和他本身的意思一樣,他從不禍害到其他的變量,但是any類型就是那種惡霸,屬于什么都不管,誰也不敢管的類型,這篇文章主要給大家介紹了關于TypeScript中unknown與any區(qū)別的相關資料,需要的朋友可以參考下2021-10-10JavaScript實現(xiàn)頁面動態(tài)驗證碼的實現(xiàn)示例
這篇文章主要介紹了JavaScript實現(xiàn)頁面動態(tài)驗證碼的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-03-03JavaScript變量聲明的var、let、const詳解
JavaScript中的變量是松散類型的,可以保存任何類型數(shù)據(jù),變量只不過是一個名稱,下面這篇文章主要給大家介紹了關于JavaScript變量聲明的var、let、const的相關資料,需要的朋友可以參考下2022-07-07JavaScript立即執(zhí)行函數(shù)的三種不同寫法
這篇文章主要介紹了JavaScript立即執(zhí)行函數(shù)的三種不同寫法,需要的朋友可以參考下2014-09-09