This article shares some of the more practical JS methods I have accumulated in daily life for your guidance and evaluation. I want to introduce it in different articles, but I found it a bit extra. I have sorted out the methods but I don’t have many ways to show it out. Of course, some of them are methods I saw online that I think are very practical. I will post them here for everyone to discuss.
1. Click to return if there is no previous page, then jump to the specified page.
First of all, the requirements of the customer's needs - a single page shared to WeChat, click to return to jump to the homepage of the website.
During this period, this function has been discussed with customers. Can you add the button to the homepage to jump to the page?
However, this method cannot work on each page, and it indicates that the sharing page that requires this function does not have the next icon, and it does not affect the beauty. So, I had to look for a tripe. The dog is also full of functions that play edge balls.
So through my own attempt, I have the following code:
//Return to the home page without a page before, return to function pushHistory() { //Get the number of records in the browser history stack //Because the current page is pushed into the stack when the page is loaded, it determines whether it is 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", ""); }}Then add the following code to the ready event on the page:
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 was a page before. If not, insert the link address of the website into the state (the home page is used here), and then listen to the popstate event to perform the corresponding function operation.
There may be some minor problems with this code, so I plan to post it and someone can discuss and improve it together.
2. Convenient logging method
I believe that everyone is already tired of console.log()'s slightly verbose length when debugging the page. Some people may use shortcut inputs to make quick inputs (such as input cl compile environment intelligently jump out of console). However, when the project is released, it will still be difficult to clear. So I simply wrote a method to deal with this situation specifically.
function lll() { //Global variable _debug is used to control the debug information switch if (_debug) { var arr = []; //arguments is the parameter set of methods. This is done to not limit the number of parameters, and facilitate debugging for (_item in arguments) { //Because personal habits that string information is displayed in a line, the string is filtered and spliced if (typeof _item == "String") { arr.push(_item) } else { console.log(_item) } } if(arr.length>0)console.log(arr.join(',')) }}Actually, I am a little dissatisfied with that I cannot automatically get the name of the parameter, otherwise I can use it like this:
var a = 123, b = 333, obj = { name: "name", content: "..." } lll(a, b, obj)//The debugging information is: a:123,b:123 //obj: //{ name: "name", content: "..." }Do you seem to understand more?
3. Obtain browser positioning information (supports mobile terminal)
Many projects I have received are customized development on mobile, so information that requires the current location to be located is often used.
However, many interfaces on the Internet need to reference an external JS section, such as Baidu's API, WeChat's API, etc.
Next, I will introduce a method that does not require reference to external js, but only needs to submit parameters to external API links to obtain positioning:
if (getCookie('position') == "") { if (navigator.userAgent.indexOf("MicroMessenger") > -1) {//Judge whether it is a WeChat terminal, depending on the situation, navigator.geolocation.getCurrentPosition(function getPositionSuccess(position) { //Get the current positioning of the browser through the navigator.geolocation interface of html5 (the mobile terminal is the most accurate, the PC will have a large deviation) var lat = position.coords.latitude;//Get the current latitude var lng = position.coords.longitude;//Get 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&callback=renderReverse&location=" + lat + "," + lng + "&output=json&pois=1",//Pass the latitude and longitude to the api provided by Baidu in the form of address bar parameters beforeSend: function () { // Since this process takes some time, it is best to have a loading prompt on the page iosload()//The page loading animation I wrote}, data: {}, dataType: "jsonp",//Since it is a cross-domain transmission, it is necessary to transmit in the form of jsonp jsonpCallback: "renderReverse",//The identity similar to cross-domain transmission requires the receiver and the transmitter to do a unified success: function (data) { ios.hide(); //alert(data) $("#myposition").html("I'm in: " + data.result.addressComponent.city) setCookie("position", data.result.addressComponent.city, 24 * 60 * 30) } }) }, function (error) { //alert(error.message); }, {}) }}This code is a piece of code in my actual project. Since I need to determine whether the targeting information has been obtained, I cannot obtain it once every time the page is loaded, so I saved the targeting information using cookies.
At the beginning, we determine whether there is a current positioning information cookie, but there is no. Then determine whether it is on the mobile terminal (because the project is from the WeChat terminal, I just did the WeChat terminal verification here)
Then call the interface parameters provided by html5 for data transmission, and the jsonp returned from Baidu is processed. Since my project only needs to obtain the location city information, I just give an example of obtaining cities.
4. Get the numerical part of the string
Because I am only responsible for the implementation of functions on the project, I do not build many pages myself, but I will also create some difficult situations in which the values in the tag are difficult to obtain.
for example:
<div>Original price of 998 is now only <a>99.8!</a> </div>
For pages like this, sometimes you need to get 998 or 98 in it. It will become a little troublesome.
Through the method I provide below, this situation can be easily solved
function getNum(text) { var value = text.replace(/[^(0-9).]/ig, ""); return parseFloat(value); }This method is very short, and it is essentially matching through regularity. Replace characters that are non-number or decimal points with empty strings (actually deleted)
The data returned in this way is the number we want. I finally converted it to a floating point operation, which is to facilitate post-processing of the data. For example, keep two decimal places, round them, etc.
5. Obtain 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 and Google kernel gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,//Firefox kernel mobile: !!u.match(/AppleWebKit.*Mobile.*/), //Is it a 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, //Is it an iPhone or QQHD browser iPad: u.indexOf('iPad') > -1, //Is it an iPad webApp: u.indexOf('Safari') == -1, //Whether the web should be a program, there is no header and bottom weixin: u.indexOf('MicroMessenger') > -1, //Whether it is WeChat (newly added on 2015-01-22) qq: u.match(//sQQ/i) == " qq" //Whether it is QQ }; }(), language: (navigator.browserLanguage || navigator.language).toLowerCase()}//The actual use is as follows: if (browser.versions.webKit) { //Code executed for Apple and Google kernel...}//#endregionHere is also a way to judge device information that I wrote and saw on the Internet.
I personally think it's very useful, so I'll share it with you.
String extension method-The following are methods to append String type data
1. Hide the part of the string beyond the specified length
/*Show the string at a specified length, and the excess is displayed in ellipses (len--Show length defaultStr--Stand string if the 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.substring(0, len) + "..."; } else { result = str; } } else { result = defaultStr; } return result;}The comments are simple enough. If you don’t understand, you can leave a message, and the blogger will reply if you see it.
2. Subtract the string length by one
//Decrement by one length String.prototype.delLast = function () { return this.substring(0, this.length - 1) }Some people may think this method is a bit suspicious of taking off their pants and farting, but in fact, this operation is often needed in real projects.
Instead of writing a long substring, we should write a method to simplify the code, and it is also very convenient to directly click the corresponding string and select delLast when coding the code.
In one sentence, it’s OK to use it!
3. Complete the specified length of the numeric string
//Fixed length for numeric strings String.prototype.addZero = function (n) { var num = this var len = num.toString().length; while (len < n) { num = '0' + num; len++; } return num;}You may not understand it when reading the comments. In fact, it is just adding this string to "2". This extension method can be used in this way. addZero(2)
Then the returned string is a string like "02".
All have said it's OK after using it!
4. Convert database DateTime type to Date
String.prototype.DTD = function () { return new Date(Date.parse(this.toString().replace(/-/g, "/"))) }5. User nickname omitted
//The user nickname omits String.prototype.telHide = function () { var name = this return name.substr(0, 1) + "****" + name.substring(name.length - 1, name.length) }The above is all about this article, I hope it will be helpful to everyone's learning.