This article shares their usual accumulation of some of the more practical JS method, for everyone to guide and evaluation. I would like to introduce a chapter, found a little superfluous. Sorted out also not a lot of the way to get shot, there are some of the Internet to see the individual feel very practical way, posted here together for everyone to discuss.
1, click to return if there is no previous page will jump to the required page
The first is the requirements of the customer requirements-a single share to the micro-letter page, click Return can jump to the homepage of the site.
This feature has been discussed with customers, can be added to the page back to the homepage button to jump.
This way, however, does not work on each page, and indicates that the shared page that needs the feature does not have the next icon, and does not affect the beauty of the place. So, I had to seek the Niang. Niang is also full of some of the functions of the ball.
So you have the following code through your own attempts:
Back to the page without
a page function pushhistory () {
//Get the number of records in the browser history stack/
/As the page loads the current page will be pushed into the stack so it is judged to be less than 2
if ( History.length < 2) {
var state = {
title: "Index",
url:gethttpprefix + "index.html"
};
Window.history.pushState (State, "index", Gethttpprefix + "index.html");
State = {
title: "Index",
URL: ""
};
Window.history.pushState (State, "index", "");
}
Add the following code to the page ready event:
settimeout (function () {
pushhistory ()
window.addeventlistener ("Popstate", function (e) {5 if ( Window.history.state!=null&&window.history.state.url!= "") {
location.href = Window.history.state.url
}
);
}, 300;
The specific function is to determine whether there is a page before, if not the establishment of the site's link address into the state (here with the home), and then listen to the Popstate event, the corresponding function of the operation.
This code may still have some minor problems, so it is intended to be posted by someone who can explore and perfect together.
2. Convenient Log method
I believe everyone page debugging is already tired of the Console.log () slightly verbose beat length. Some people may use shortcut input for quick input (e.g., input CL compilation environment Smart Jump console). However, when the project is released to see a lot of forgotten to delete debugging information, or it will be difficult to clear. So I simply wrote a method to deal with this situation.
function lll () {
//global variable _DEBUG is used to control the debug information switch
if (_DEBUG) {
var arr = [];
Arguments is a set of parameters for a method to do so in order not to limit the number of arguments, to facilitate debugging for
(_item in arguments) {
////Because personal habits string information is displayed on one line so the string is filtered to concatenation
if (typeof _item = = "String") {
Arr.push (_item)
} else {
console.log (_item)
}
}
if (arr.length>0) Console.log ( Arr.join (', ')
}
}
In fact, a little dissatisfied is not the way to automatically get the name of the parameter or you can use this:
var a = 123, B = 333, obj = {name: "name", Content: "..."}
LLL (A, B, obj)//debug information is: a:123,b:123
//obj:
//{Name: "Name", Content: "..."}
Does it seem to be a little more clear?
3, get the browser positioning information (support mobile side)
Many of the items you receive are custom developed by the mobile side, so you often use information that requires locating the current location.
However, many of the Internet interfaces are required to refer to a section of external JS, such as Baidu's API, micro-mail APIs and so on.
I'm going to introduce a method that does not need to refer to external JS, only to submit parameters to the external API link to get the location:
if (GetCookie (' position ') = = "") {if (Navigator.userAgent.indexOf ("Micromessenger") >-1) {//To determine whether the micro-letterhead, depending on the circumstances Navigator.geolocation.getCurrentPosition (function getpositionsuccess (position) {//through HTML5 Navigator.geolocati On interface to get the current positioning of the browser (the most accurate mobile end, PC will have a large deviation) var lat = position.coords.latitude;//Get over the current latitude var lng = Position.coords
. longitude;//get over the current longitude var arr = [] Arr.push (LNG) arr.push (LAT)//alert (position) $.ajax ({type: "Get", url: "Http://api.map.baidu.com/geocoder/v2/?ak=oM55dVWVwLUU7shkz7uY8M6E&call
back=renderreverse&location= "+ Lat +", "+ LNG +" &output=json&pois=1 ",//latitude and longitude through the address bar parameters to the form of the API provided by Baidu
Beforesend:function () {//Because this process takes some time so the best page has load prompts iosload ()/I write the page load animation}, Data: {}, DataType: "Jsonp",//because it is cross-domain transport, it needs to be transported in JSONP form jsonpcallback: "Renderreverse",//The identity of a cross-domain transmission needs to be answered Deceptions and transmission side do the unification sucCess:function (data) {ios.hide (); Alert (data) $ ("#myposition"). HTML ("I am in:" + data.result.addressComponent.city) Setcookie ("position ", Data.result.addressComponent.city, *)}}", function (Error) {//alert (error.mess
Age);
}, {})
}
}
This code is my actual project in a piece of code, because need to determine whether the location information has been obtained, not every page load to do a fetch so I use cookies to save the location information
At the beginning of the time to determine whether there is the current positioning information cookie, No. To determine whether it is on the mobile side (because the project is a micro-client, so I just do a micro-client verification)
Then call HTML5 to provide the interface parameters for data transmission, Baidu returned JSONP processing. Since my project only needs to get the location of the city information so here is just the example of getting the city.
4. Get the string value part
Because I am only responsible for the implementation of the function, so many pages are not my own, but there will be some novice to build some very difficult to get the value of the tag in the case.
Like what:
<div> Original price 998 now as long as
<a>99.8!</a>
</div>
Like this page, sometimes to get inside 998 or 98. It's going to get a little bit messy.
This situation can be easily solved by the method I provide below.
function Getnum (text) {
var value = Text.replace (/[^ (0-9).] /ig, "");
return parsefloat (value);
}
This method is very short, in essence, is to match through the regular. Replaces a character that is not a number or a decimal point with an empty string (which is actually deleted)
So the data returned was the number we wanted, and I finally made a conversion to a floating-point type, which was to facilitate post-processing of the data. For example, keep two decimal places, rounding and so on.
5, getting device information
#region Get device information var browser = {Versions:function () {var u = navigator.useragent, app = Navigator.appversion;
return {trident:u.indexof (' Trident ') >-1,//ie kernel presto:u.indexof (' presto ') >-1,//opera kernel Webkit:u.indexof (' AppleWebKit ') >-1,//Apple, Google kernel gecko:u.indexof (' Gecko ') >-1 && u.indexof (' khtml ') ) = = -1,//Firefox kernel mobile:!! U.match (/applewebkit.*mobile.*/),//Whether for Mobile terminal iOS:!! U.match (/\ (i[^;] +;( U;)? Cpu.+mac OS x/),//ios terminal Android:u.indexof (' Android ') >-1 | | U.indexof (' Linux ') >-1,//android terminal or UC Browser iphone:u.indexof (' IPhone ') >-1,//whether for IPhone or Qqhd browser iPad: U.indexof (' ipad ') >-1,//whether the ipad webapp:u.indexof (' Safari ') = = 1,//whether the Web should program, no head and bottom weixin:u.indexof (
' Micromessenger ') >-1,//whether micro-letter (2015-01-22 added) qq:u.match (/\sqq/i) = = "QQ"/whether QQ}; (), Language: (Navigator.browserlanguage | | navigator.language). toLowerCase ()}//actual use is as follows: if (broWser.versions.webKit) {//The code executed for Apple's Google kernel ...}
#endregion
This is also a way of sharing information that is not written by me and is also seen on the Internet as an object-determining device.
Personally feel very easy to use, so also to share with you.
String extension methods--all of the methods attached to string type data are described below
1. Hide the string beyond the specified length
/* Displays the string in the specified length, with the remainder shown in ellipses (len--display length
defaultstr--if string is empty)
* * *
String.prototype.splitString = function (len, defaultstr) {
var result = "";
var str = this.tostring ()
if (str) {
str = Str.trim ()
if (Str.length > Len) {result
= Str.substrin G (0, Len) + "...";
}
else {result
= str;
}
}
else {result
= Defaultstr;
}
return result;
}
The comment is simple enough. Do not understand can leave a message, the blogger see a certain reply.
2. Reduce the length of the string by one
Length minus one
String.prototype.delLast = function () {return
this.substring (0, this.length-1)
}
Some people may feel that this method is a bit off the hook to fart, in fact, the real project will often need this operation.
Rather than writing a long substring, we should write a method to simplify the code, and in the code when it is convenient to directly behind the corresponding string of strings, select Dellast on the line.
In a word, used to all say yes!
3. Specify the length of the numeric string complement
Fixed specified length to numeric string
String.prototype.addZero = function (n) {
var num = this
var len = num.tostring (). length;
while (Len < n) {
num = ' 0 ' + num;
len++;
}
return num;
}
Look at the annotation may be a little bit not understand actually is to add this string is "2", through this extension method can do so "2". Addzero (2)
So what comes back is a string like "02".
You used to say yes!
4. Convert database datetime type to date
String.prototype.DTD = function () {return
new Date (Date.parse (this.tostring (). Replace (/-/g, "/"))
}
5. User nickname omitted
User Nickname omitted
String.prototype.telHide = function () {
var name = This return
name.substr (0, 1) + "* * *" + name.sub String (name.length-1, name.length)
}
The above is the entire content of this article, I hope to help you learn.