Some highly practical js method_javascript skills

Source: Internet
Author: User
This article mainly shares some highly practical js methods for your convenience during development, interested friends can refer to this article to share some of the highly practical js methods they have accumulated for your guidance and comments. I wanted to introduce it in several articles, and I found it a little superfluous. I have sorted out a few methods that I can use. Naturally, some of them are actually practical methods that I personally find online. I will post them here for discussion.

1. Click to return. If no previous page exists, the page will jump to the required page.

The first is the requirement in customer requirements-a single shared page. Click Back To go to the homepage of the website.

During this period, this feature has been discussed with the customer, whether to add back to the home page button in the page to jump.

However, this method does not work on every page, and it specifies that the sharing page that requires this function cannot be placed in the next icon without affecting the appearance. As a result, I had to look for du Niang. Du Niang also has some features to play the edge Ball.

Therefore, the following code is available for your attempt:

// If no page is returned, return the Home Page function pushHistory () {// obtain the number of records in the browser history record stack. // when the page is loaded, the current page is pushed into the stack, so it is determined 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 ","");}}

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 is a page before, if not, insert the URL of the website into the state (the home page is used here), then listen to the popstate event, and perform corresponding function operations.

This code may have some minor issues, so it is intended that someone can discuss and improve it together.

2. Convenient log method

I believe that you will get bored with the console. log () hitting length when debugging pages. Some may use Quick input for quick input (for example, input cl compiling environment to intelligently jump out of the console ). However, when the project is released, it will still be difficult to clear a lot of debugging information that you forget to delete. So I simply wrote a method to handle 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 of the method. in this way, you can debug for (_ item in arguments) without limiting the number of parameters) {// as the String information is displayed in one row, 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 (','))}}

In fact, it is not satisfactory that the parameter name cannot be automatically obtained. Otherwise, you 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: "... "}

Does it seem more clear?

3. Obtain browser positioning information (mobile terminals supported)

Many projects are customized and developed on the Mobile End. Therefore, you often need to locate the current location.

However, many interfaces on the internet need to reference an external js such as Baidu's api and api.

Next, I will introduce a method to obtain the location by submitting parameters to the external API link without referencing external js:

If (getCookie ('position') = "") {if (navigator. userAgent. indexOf ("MicroMessenger")>-1) {// determines whether it is an end. The navigator depends on the actual situation. geolocation. getCurrentPosition (function getPositionSuccess (position) {// use the html5-based navigator. the geolocation interface obtains the current location of the browser (the mobile end is the most accurate, and the PC has a large deviation) var lat = position. coords. latitude; // The obtained current latitude var lng = position. coords. longpolling; // obtain 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 ", // send the latitude and longitude to the api beforeSend: function () provided by Baidu in the form of address bar Parameters () {// This process takes some time, so it is best to have the loading prompt iosload () // I wrote the page loading animation}, data :{}, dataType: "jsonp ", // because it is a cross-origin transmission, jsonpCallback: "renderReverse" needs to be transmitted in the form of jsonp. // The identifier similar to that for cross-origin transmission must be consistent between the receiver and the transmitter. success: function (data) {ios. hide (); // alert (data) $ ("# myposition" ).html ("I am at:" + 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. Because I need to determine whether the location information has been obtained and cannot be obtained every time the page is loaded, I used cookies to save the location information.

At the beginning, determine whether the current location information cookie exists. Then determine whether it is on the Mobile End (because the project is on the end, I just did the verification here)

Then, call the interface parameters provided by html5 for data transmission and process the jsonp returned by Baidu. In my project, I only need to obtain the information of the target city, so here is just an example of how to get the information of the target city.

4. Obtain the string value

I am only responsible for implementing functions in the project, so many pages are not built by myself, but some new users may not be able to obtain the values in the tag.

For example:

The original price of 998 is only 99.8 now!

For pages like this, you sometimes need to get 998 or 98. It will become a little troublesome.

Through the methods provided below, we can easily solve this problem.

 function getNum(text) {   var value = text.replace(/[^(0-9).]/ig, "");   return parseFloat(value); }

This method is very short. In essence, it is matched by regular expressions. Replace non-numeric or decimal character with an empty string (actually delete it)

In this way, the returned data is the number we want, and I finally switched to the floating point type for later processing. For example, keep two decimal places and rounding them.

5. Get device information

// # Region obtain the device information var browser = {versions: function () {var u = navigator. userAgent, app = navigator. appVersion; return {trident: u. indexOf ('think')>-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 it is 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, // whether the browser is iPhone or QQHD iPad: u. indexOf ('ipad ')>-1, // whether iPad webApp: u. indexOf ('safari ') =-1, // whether the web should program with no header and weixin: u. indexOf ('micromessenger ')>-1, // do you want to add qq: u. match (/\ sQQ/I) = "qq" // QQ?};} (), language: (navigator. browserLanguage | navigator. language ). toLowerCase ()} // the actual usage is as follows: if (browser. versions. webKit) {// code executed for the Apple Google kernel ...} // # endregion

Here we also share a method of judging device information that is encapsulated into an object that I did not write or seen on the Internet.

I personally think it is very useful, so I will share it with you.

String extension method-the following describesMethod for attaching String data

1. Hide a string that exceeds the specified length

/* Display the String with the specified length, and display the excess part with a ellipsis (len -- display the defaultStr length -- if the String is null) */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 ;}

Annotations are simple and clear. If you don't understand it, you can leave a message. The blogger will receive a reply.

2. Reduce the string length by one

// Length minus one String. prototype. delLast = function () {return this. substring (0, this. length-1 )}

Some people may think that this method is a bit difficult to put off your pants and fart. In fact, this operation is often required in real projects.

Instead of writing a long substring, we can write a method to streamline the Code. In addition, when coding, It is very convenient to simply click a bit behind the corresponding string, just select delLast.

In a word, I always say yes!

3. Add the number string to the specified length

// Specify the String length for the numeric String. prototype. addZero = function (n) {var num = this var len = num. toString (). length; while (len <n) {num = '0' + num; len ++;} return num ;}

The comment may not be understood. In fact, it is added to the string "2". This extension method can be used to perform the "2". addZero (2) operation)

The returned string is a string like 02.

If you have used it, say yes!

4. Convert the DateTime type of the database to Date

 String.prototype.DTD = function () {   return new Date(Date.parse(this.toString().replace(/-/g, "/"))) }

5. Nickname omitted

// The user nickname is omitted String. prototype. telHide = function () {var name = this return name. substr (0, 1) + "*****" + name. substring (name. length-1, name. length )}

The above is all the content of this article, hoping to help you learn.

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.