Sharing JavaScript, jquery practical code Snippets _javascript tips

Source: Internet
Author: User
Tags numeric numeric value stack trace throw exception unique id sessionstorage

This article examples for everyone to share a simple JavaScript, jquery practical demo, for your reference, the specific contents are as follows

JavaScript Judge H5 Page left

function Onbeforeunloadfn () {
 console.log (' leave page ');
 ... code
}
function Showonbeforeunload (flags) {
 if (flags) {
 document.body.onbeforeunload = ONBEFOREUNLOADFN;
 } else{
 document.body.onbeforeunload = null;
 }
$ (function () {
 showonbeforeunload (true);
})

JQ determine if the IMG tag picture address has been loaded

Imgstatus = 0;
 $ ("img"). each (function () {
 if (this.complete) {/*this.complete on behalf of picture loading complete/
  imgstatus++;
 }
 );

IFrame get content-and settings

if ($ (". Ad_show iframe"). Size () > 0) {
 $ (". Ad_show iframe"). attr ("id", "iframead");/* Set iframe id*//*
 Gets the DOM object for the IFRAME with ID iframead
 /var iframebox = document.getElementById ("Iframead"). Contentwindow;
 /* Set Fallback content * *
 iframebox.document.body.innerText = "1234";
}

JavaScript gets the URL of a page on the browser

 /* Returns the last URL, if it is a new window can not get to * *
var beforeurl = document.referrer;

Mobile-side Click bubbling event on 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 prevent most bubbling events, there are still a small number of mobile terminals that do not eat your set, then there is another solution * * To control the event between tiers through the H5 property data-flag= "True" for controlling/<!-- html--> <div class= "Parenttap" data-flag= "true" > <div class= "Childtap" data-flag= "false" > <div class = "Childstap" data-flag= "false" > ... </div> </div> </div> <!--bind a click event to the parent Parenttap--> < !--bind a Click event to a child Childtap--> <!--bind a click event to a descendant Childstap--> <script type= "Text/javascript" > var bindinit = function (ClassName) {if ($ (className). Size () > 0) {$ (ClassName). On (' Tap ', function (oevent) {e = window.event | | oeve Nt;if (e.stoppropagation) {e.stoppropagation ();} Else{e.cancelbubble = true;}
  E.preventdefault ();
  var flag = $ (this). Data (' flag ');
 if (flag) {/* is true, allow click into Event/* Code ... * } $ (function () {BindinIt ('. Parenttap ');
 Bindinit ('. Childtap ');
 Bindinit ('. Childstap ');
}); </script>

Simple countdown feature

<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" > * * Countdown/var Timedown = {Getrtime:function (timeid,oldnowtime) { var temptime;/* save last time/if (oldnowtime) {temptime = new Date (oldnowtime.gettime () + 1000);/* If there is a previous time then the value is assigned/*/*cons Ole.log (temptime); */} var endtime = new Date ($ ("#" + Timeid). Data ("End");/* Get Ending Time */if (!temptime) {if ($ ("#") + Timeid). Data ("now") = = "" | |
   $ ("#" + Timeid). Data ("now") = = "Null") {var nowtime = new Date ();
  else {var nowtime = new Date ($ ("#" + Timeid). Data ("Now");/"Fetch start time * *"}} else {var nowtime = Temptime; } if (Endtime.gettime () >= nowtime.gettime ()) {/* judgment time/var t = endtime.gettime ()-nowtime.gettime (); * Get end time minus start Time stamp */var d = Math.floor (t/1000/60/60/24);//* Day/var h = Math.floor (t/1000/60/60% 24);/* Time/var m = Math.floor (t/1000/60% 60);/*/var S = Math.floor (t/1000% 60),//////////////////////////////* (". 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);/* will start time +1 seconds/settimeout (function () {Timedown.getrtime (timeid,nowtime
  * * Wait one second to continue executing */}, 1000);
  An else if (endtime.gettime () = = Nowtime.gettime ()) {/* code*/$ ("#" +timeid) to be processed when the time is equal. Hide ();
 }} var t=0;
  if ($ (". NewTime"). Size () > 0) {$ (". NewTime"). each (function () {var timeid= "timeOut" +T;
  $ (this). attr ("id", Timeid);/* Specify unique id*/t++ when setting multiple countdown times;
 Timedown.getrtime (timeid,null);/* Start call/}); } </script>

Node operations for jquery

Jquery.parent (expr)/* Find a Father node that can be filtered by expr, such as $ ("span"). Parent () or $ ("span"). Parent (". Class")/

jquery.parents ( Expr)/* is similar to jquery.parents (expr), but is to find all ancestor elements, not limited to the parent element

/Jquery.children (expr)/* Return all child nodes, this method will only return the direct child node, Will not return all Descendants node

/jquery.contents ()/* Returns all of the following, including nodes and text. The difference between this method and children () is that, including blank text, it is also returned as A/

*
 JQuery object, Children () returns only the node

 Jquery.prev () and returns to the last sibling node. Not all sibling nodes

 Jquery.prevall (), return all previous sibling nodes

 Jquery.next (), return to the next sibling node, not all sibling nodes

 Jquery.nextall (), Returns all subsequent sibling nodes

 Jquery.siblings (), returning sibling nodes,

 jquery.find (expr), completely different from jquery.filter (expr).
 Jquery.filter () is a part of the initial collection of JQuery objects,
 and the return result of Jquery.find () does not have the contents of the initial collection,
 such as $ ("P"), Find ("span"), is to start looking for <span> from the <p> element, equal to $ ("P span")
* *

In syntax in the IF judgment statement in JS

/*
in the JS code, the
usual if judgment statement will write:
* *
if (1 = = 1) {
 alert ("1 equals 1");
} else{
 Alert ("1 does not equal 1");
}
/* And in the writing can be like this: */
if (1 in window) {
 alert ("window contains 1");
} else{
 alert ("window does not contain 1");
}

JS's 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);}
 /* Change JS code will catch an exception error: because Foo.bar (); is undefined;
 So in the JS code if there is no exception capture, the entire page will not continue parsing.
 This causes the page to load to fail. 
 Here it is necessary to Try-catch to catch this error, and give him back to the present we may get the system anomaly mainly contains the following 6 kinds: evalerror:raised When a error occurs executing code in eval () Translation: When an error occurs in the eval () execution code rangeerror:raised when a numeric variable or parameter be outside of its valid range translation: When a numeric value Outside the valid range of a variable or parameter referenceerror:raised when de-referencing a invalid reference translation: Reference Invalid reference syntaxerror:raised when a SYN  Tax 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 Para 
 Meters translation: When calling encodeURI () or decodeURI (), the passed parameter is not passed invalid the following is an exception capture attribute: Error has some of the following primary properties: Description: Error description (ie only available). 
 FileName: The file name of the error (Mozilla only available).LineNumber: The number of rows that failed (Mozilla only available). 
 Message: Error information (in IE below description) Name: Error type. 
 Number: Error code (ie only available).
Stack: Error stack information like stack trace in Java (only Mozilla is available).  * * * To determine the type of exception information, you can judge 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);
 }
}

The difference between TypeOf and instanceof in JS

/* First catch exception, throw exception */
try {
 throw new Myblur ();///Throw 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 ()//executes this method, outputting the "Lost Focus"
 }else{
 Console.log ("Not a Function method")
 ;
}
function Myblur () {
 THIS.A = function () {
 Console.log ("Lost Focus");
 }
 /* Unobstructed typeof generally can only return the following several results:
 number,boolean,string,function,object,undefined;
 If you want to compare with if, compare the following with double quotes (
 typeof (param) = = "Object") {
 alert ("This parameter equals object type");
 } else{
 alert ("This parameter is not equal to object type");
 }

/* Also such as: * *
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 Cache Sessionstorage

Sessionstorage.getitem (key)//Get the value of the specified key locally stored
Sessionstorage.setitem (key,value)//To store value in the key field
Sessionstorage.removeitem (key)//deletes the number of items locally stored by the specified key
sessionstorage.length//sessionstorage/

*
Similarities and differences between Sessionstorage and Localstorage:
 sessionstorage and Localstorage in a different place, the
 storage of sessionstorage data is specific to only one session.
 This means that the data is only kept until the browser is closed, and the previous storage has been cleared when the browser is closed and the page is reopened.
 while Localstorage is a persistent storage, it is not limited

to the local storage data used by the session Sessionstorage and Localstorage Clear () function to purge the same origin:
 For example, Localstorage.clear (), which deletes all native-stored localstorage data,
 and for Sessionstorage, it empties only the data stored by the current session.

Sessionstorage and Localstorage have the same method storage event: The
 stored action cannot be canceled in the handler function of the stored event.
 storage events are just a notification that the browser gives you after the data change occurs. The
 storage event is triggered when SetItem (), RemoveItem (), or the clear () method is invoked,
 and the data really changes.
 Notice that the condition here is that the data really changed. In other words,
 if the current storage area is empty, you can call clear () without triggering the event.
 or you can set a value that is the same as an existing value by SetItem (), and the event will not be triggered.
 when the storage area changes, it is triggered.
*/

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.