Share the javascript and jquery useful code snippet, javascriptjquery

Source: Internet
Author: User
Tags sessionstorage

Share the javascript and jquery useful code snippet, javascriptjquery

The examples in this article are as follows:

Javascript determines H5 page exit

Function onbeforeunloadFn () {console. log ('exit page ');//... code} function showOnbeforeunload (flags) {if (flags) {document. body. onbeforeunload = onbeforeunloadFn;} else {document. body. onbeforeunload = null ;}$ (function () {showOnbeforeunload (true );})

Jq checks whether the image address of the img label has been loaded.

ImgStatus = 0; $ ("img "). each (function () {if (this. complete) {/* this. complete indicates that the image has been loaded */imgStatus ++ ;}});

Iframe get content-and settings

If ($ (". ad_show iframe "). size ()> 0) {$ (". ad_show iframe "). attr ("id", "iframead");/* set the iframe id * // * Get the dom object of iframe whose id is iframead */var iframebox = document. getElementById ("iframead "). contentWindow;/* set the bottom content */iframebox.doc ument. body. innerText = "1234 ";}

Javascript to get the url of the browser's previous page

/* Returns the last url. If it is a new window, it cannot be obtained */var beforeUrl = document. referrer;

Click bubble events on mobile terminals with headaches

<Script> $ (". class "). live ('tap', function (oEvent) {e = window. event | oEvent; if (e. stopPropagation) {e. stopPropagation ();} else {e. cancelBubble = true;} e. preventDefault () ;}); </script>/* although the tap event can block most of the bubble events, a small number of mobile terminals will not eat this set, there is another solution * // * to control inter-level events through the H5 attribute data-flag = "true" */<! -- Html --> <div class = "parentTap" data-flag = "true"> <div class = "childTap" data-flag = "false"> <div class = "childsTap "data-flag =" false "> .... </div> <! -- Bind a click event to the parent parentTap --> <! -- Bind a click event to the Child childTap --> <! -- Bind a click event to the Child 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) {/* is true, click to enter the event * // * code... */}) ;}}$ (function () {bindInit ('. parentTap '); bindInit ('. childTap '); bindInit ('. childsTap ');}); </script>

Simple countdown Function

<Div class = "newTime" data-end = "23:59:59" data-now = "03:59:59"> <div class = "t_d"> </div> <div class = ""t_h"> </div> <div class = "t_m"> </div> <div class = "t_s"> </div> <script type = "text/javascript">/* countdown */var timeDown = {GetRTime: function (timeId, oldNowTime) {var tempTime;/* save the last time */if (oldNowTime) {tempTime = new Date (oldNowTime. getTime () + 1000);/* assign a value if the previous time exists * // * console. l Og (tempTime); */} var EndTime = new Date ($ ("#" + timeId ). data ("end");/* Get end time */if (! TempTime) {if ($ ("#" + timeId ). data ("now") = "" | $ ("#" + timeId ). data ("now") = "null") {var NowTime = new Date ();} else {var NowTime = new Date ($ ("#" + timeId ). data ("now");/* get start time */} else {var NowTime = tempTime;} if (EndTime. getTime ()> = NowTime. getTime () {/* Judgment time */var t = EndTime. getTime ()-NowTime. getTime ();/* get the end time minus the start time timestamp */var d = Math. floor (t/1000/60/60/24);/* day */va R h = Math. floor (t/1000/60/60% 24);/*/var m = Math. floor (t/1000/60% 60);/* points */var s = Math. floor (t/1000% 60);/* seconds * // enter the time in the corresponding html */$ (". t_d "," # "+ timeId).html (d> 9? '': '0') + d); $ (". t_h "," # "+ timeId).html (h> 9? '': '0') + h); $ (". t_m "," # "+ timeid1_.html (m> 9? '': '0') + m); $ (". t_s "," # "+ timeId).html (s> 9? '': '0') + s); tempTime = new Date (NowTime. getTime () + 1000);/* Start Time + 1 second */setTimeout (function () {timeDown. getRTime (timeId, NowTime);/* wait for a second and continue executing */}, 1000);} else if (EndTime. getTime () = NowTime. getTime () {/* code to be processed when the time is equal */$ ("#" + timeId ). hide () ;}} var t = 0; if ($ (". newTime "). size ()> 0) {$ (". newTime "). each (function () {var timeId = "timeOut" + t; $ (this ). attr ("id", timeId);/* specify a unique id */t ++ when setting multiple countdown times; timeDown. getRTime (timeId, null);/* start to call */});} </script>

JQuery node operations

JQuery. parent (expr)/* for Father's Day, you can pass in expr for filtering, such as $ ("span "). parent () or $ ("span "). parent (". class ") */jQuery. parents (expr)/* is similar to jQuery. parents (expr), but is used to search for all ancestor elements, not limited to parent elements */jQuery. children (expr)/* returns all child nodes. This method only returns the direct child node and does not return all child nodes */jQuery. contents ()/* returns all the following content, including the node and text. The difference between this method and children () is that, including blank text, it will also be returned as a * // * jQuery object, and children () will only return the node jQuery. prev (), returns the previous sibling node, not all sibling nodes jQuery. prevAll (), returns all previous sibling nodes jQuery. next (), return to the next sibling node, not all sibling nodes jQuery. nextAll (), returns all the following sibling nodes jQuery. siblings (), returns the sibling node, regardless of the front and back jQuery. find (expr), with jQuery. filter (expr) is completely different. JQuery. filter () is to filter a part from the initial jQuery object set, while jQuery. NO content in the initial set is returned for find (), for example, $ ("p"), find ("span "), is to start from the <p> element to find <span>, equivalent to $ ("p span ")*/

The in syntax in the if judgment statement in js

/* In js Code, the if judgment statement is usually written as follows: */if (1 = 1) {alert ("1 = 1 ");} else {alert ("1 is not equal to 1");}/* but in the in statement, you can do this: */if (1 in window) {alert ("window contains 1");} else {alert ("window does not contain 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);}/* When the js Code is changed, an exception error will be caught: Because foo. bar (); is undefined. Therefore, if no exception is caught in the js Code, the entire page will not be parsed. as a result, page loading fails. here we need to catch this error through try-catch and report it to him. Currently, the possible system exceptions include the following six types: EvalError: raised when an error occurs executing code in eval () Translation: when an error occurs in eval () Execution code RangeError: raised when a numeric variable or parameter is outside of its valid range Translation: when a value variable or parameter is out of the valid range of ReferenceError: raised when de-referencing an invalid reference Translation: reference invalid reference SyntaxError: raised when a syntax error occurs while parsing code in eval () Translation: syntax error. when a syntax error occurs in the eval () parsing code, TypeError: raised when a variable or parameter is not a valid type Translation: Error type: when a variable or parameter is not a valid type URIError: raised when encodeURI () or decodeURI () are passed invalid parameters Translation: When you call encodeURI () or decodeURI (), the passed parameters are invalid. The following are the properties of exception Capture: Error has the following main attributes: description: error description (IE only ). fileName: indicates the file name with an error (available only for Mozilla ). lineNumber: Number of wrong lines (available only for Mozilla ). message: error message (description in IE) name: Error type. number: Error Code (IE only ). stack: Error Stack information similar to the stack Trace in Java (available only by Mozilla ). * // * to determine the type of exception information, you can make a judgment in catch: */try {coo. bar (); // catch exception, ReferenceError: Reference invalid reference} 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 );}}

Differences between typeof and instanceof in js

/* Capture exceptions first and throw exceptions */try {throw new myBlur (); // throw the current object} catch (e) {console. log (typeof (e. a); // returns the function type if (e. a instanceof Function) {// instanceof is used to determine whether a variable is an instance of an object, true console. log ("is a function method"); e. a (); // execute this method and output "no focus"} else {console. log ("not a function method");} function myBlur () {this. a = function () {console. log ("no focus") ;};}/* unobstructed typeof Generally, only the following results can be returned: number, boolean, string, function, object, undefined; if you want to use if for comparison, double quotation marks will be used after comparison */if (typeof (param) = "object") {alert ("this parameter is equal to object type ");} else {alert ("this parameter is not of the object type");}/* For example: */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 cache sessionStorage

SessionStorage. getItem (key) // gets the sessionStorage value of the local storage of the specified key. setItem (key, value) // store the value to the key field sessionStorage. removeItem (key) // Delete the sessionStorage value of the local storage of the specified key. length // Number of sessionStorage projects/* similarities and differences between sessionStorage and localStorage: sessionStorage and localStorage are different. The storage of sessionStorage data is only specific to a session, that is to say, the data is only closed in the browser. When the browser closes and re-opens the page, the previous storage has been cleared. LocalStorage is a persistent storage, which is not limited to the clear () function of session sessionStorage and localStorage for clearing local storage data of the same source: for example, localStorage. clear (), which deletes all localStorage data stored locally in the same source. For SessionStorage, it only clears the data stored in the current session. SessionStorage and localStorage share the same storage event Method: you cannot cancel this storage action in the processing function of the storage event. The storage event is only a notification sent to you by the browser after data changes occur. When the setItem (), removeItem (), or clear () method is called and the data changes, the storage event is triggered. Note that the condition here is that the data has actually changed. That is to say, if the current storage region is empty, you will not trigger the event by calling clear. Alternatively, if you use setItem () to set a value that is the same as the existing value, the event will not be triggered. It is triggered when the storage area changes. */

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.