Some practical js methods

  • 2021-02-17 06:11:26
  • OfStack

This paper shares their usual accumulation of 1 practical js method, for everyone to guide and evaluation. I wanted to introduce each article, but found that it was a bit gilding the lily. Organized the next is not much to take the hand of the method, there are some natural online to see the personal feel very practical method, here 1 posted out for everyone to discuss.

1. Click to return to the specified page if there is no previous page

The first is the requirement of customer demand - a single page shared to WeChat, click back can jump to the website home page.

This function has been discussed with the customer during the period, whether we can add a back home button to the page for jumping.

But this way can not work on every page, and indicates that the need for the function of the sharing page can not be placed next to an icon, and does not affect the beauty of the place. Then, oneself had to be to seek Baidu. Baidu is also full of marginal features.

So I have the following code through my own experiment:


// Return to the home page if there is no page before 
function pushHistory() {
  // Gets the number of records in the browser history stack 
  // The current page is pushed onto the stack when the page loads   So let's see if it's 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:


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 judge whether there is a page before, if not, the link address of the website will be inserted into state (here is the home page), and then listen to popstate events, the operation of the corresponding function.

This code may have a few minor problems, so I'm going to post it for someone to discuss and improve.

2. Convenient log method

Believe everyone page debugging time already bored console. log () the beat length of � windbag slightly. Some people may use shortcut input for quick input (e.g., enter ES32en compiler intelligently to jump out of ES33en). However, when you wait until the project is released and see a lot of debug information that you forgot to delete, it will still be difficult to erase. So I wrote a method specifically to deal with this situation.


function lll() {
  // The global variable _debug Used to control the debug information switch 
  if (_debug) {
    var arr = [];
    //arguments Is a collection of parameters for a method   This is done in order not to limit the number of parameters and to facilitate debugging 
    for (_item in arguments) {
      // Because the personal custom string information is displayed in 1 So the string is filtered and concatenated 
      if (typeof _item == "String") {
        arr.push(_item)
      } else {
        console.log(_item)
      }
    }
    if(arr.length>0)console.log(arr.join(','))
  }
}

There is no way to automatically get the name of the parameter otherwise you can use it like this:


var a = 123, b = 333, obj = { name: "name", content: "..." }
 lll(a, b, obj)// Debugging information is:  a:123,b:123
        //obj:
        //{ name: "name", content: "..." }

Doesn't that make a little bit more sense?

3. Obtain browser location information (mobile terminal is supported)

Many projects received are customized for mobile terminal development, so the information needed to locate the current location is often used.

However, many interfaces on the Internet are required to refer to a section of external js, such as Baidu api, WeChat api and so on.

Instead of referring to the external js, I will present a method that simply submits parameters to the external API link to get the location:


if (getCookie('position') == "") {

    if (navigator.userAgent.indexOf("MicroMessenger") > -1) {// Whether it is a WeChat end depends on the situation 
      navigator.geolocation.getCurrentPosition(function getPositionSuccess(position) {
        // through html5 the navigator.geolocation interface   Gets the current location of the browser   (Mobile is the most accurate, PC There will be a big deviation) 
        var lat = position.coords.latitude;// Get the current latitude 
        var lng = position.coords.longitude;// The current longitude obtained 
        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 in the form of the address bar parameter   Pass to baidu to provide api
          beforeSend: function () {
            // Because this process takes some time   So it's better to have a load prompt on the page 
            iosload()// I write the page load animation 
          },
          data: {},
          dataType: "jsonp",// Because it's a cross-domain transfer   So you need to take jsonp The form of the transmission 
          jsonpCallback: "renderReverse",// An identity similar to a cross-domain transport   Requires the receiver and the transmitter to unify well 1
          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. Because I need to judge whether the location information has been obtained, I cannot obtain it once every time the page is loaded, so I save the location information with ES57en

At the beginning, check if there is current location information cookie, no. Then judge whether it is on the mobile terminal (since the project is at WeChat terminal, I only verified it aWeChatB1 terminal here).

Then call html5 to provide interface parameters for data transmission, Baidu will return to jsonp processing. In my project, I only need to obtain the city information of positioning, so here I just give the example of obtaining the city.

4. Get the value part of the string

Since I was only responsible for the implementation of the function on the project, I didn't create many pages myself, but there were some unskilled people who made it difficult to get the values in the tags.

Such as:


<div> The original price 998 Now, as long as 
  <a>99.8!</a>
 </div>

For pages like this, sometimes you need to get the 998 or 98 inside. It's going to get a little messy.

This situation can be easily solved by the methods I provide below


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

This is a very short method, and it's essentially a regular match. Replace non-numeric or decimal characters with empty strings (in effect, delete)

In this way, the data returned was the number we wanted, and I finally converted it to floating point once more, in order to facilitate the post-processing of the data. You keep two decimals, you round off four and you round off five, and so on.

5. Obtain equipment information


//#region  Obtain device information 

var browser = {
  versions: function () {
    var u = navigator.userAgent, app = navigator.appVersion;
    return {
      trident: u.indexOf('Trident') > -1, //IE The kernel 
      presto: u.indexOf('Presto') > -1, //opera The 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 The browser 
      iPhone: u.indexOf('iPhone') > -1, // Whether it is iPhone or QQHD The browser 
      iPad: u.indexOf('iPad') > -1, // Whether or not iPad
      webApp: u.indexOf('Safari') == -1, // Whether or not web Should program, no head with bottom 
      weixin: u.indexOf('MicroMessenger') > -1, // Whether WeChat   ( 2015-01-22 New) 
      qq: u.match(/\sQQ/i) == " qq" // Whether or not QQ
    };
  }(),
  language: (navigator.browserLanguage || navigator.language).toLowerCase()
}

// When used in practice: 
if (browser.versions.webKit) {
  // For apple   The code executed by the Google kernel ...
}

//#endregion

This is also a way to share information about a device that is not written by me but is also encapsulated in an object that I read online.

Personally feel very easy to use, so also brought with you to share 1.

String extension methods - The following are methods for appending data of type String

1. Hide parts of a string that exceed the specified length


/*
 Displays the string at the specified length, and the remainder with an ellipsis ( len-- According to the length of the 
defaultStr-- String to be displayed 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;
}

Comments are simple enough. If you don't understand, you can leave a message, and the blogger will see a reply.

2. Decrease the length of the string by 1


// The length of the cut 1
 String.prototype.delLast = function () {
   return this.substring(0, this.length - 1)
 }

Some people might think this is a bit of a pants down fart, but it's often needed on real projects.

Instead of writing a long substring, let's write a method to simplify the code and make it easier to code it. Just click delLast after the corresponding string.

1 words, used all say good!

3. Complements a numeric string with the specified length


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);

0

It's just adding the string "2", and using this extension we can do "2".addZero (2)

So you get back a string like "02".

Used all say yes!

4. Convert DateTime to Date


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);

1

5. User nickname omission


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);

2

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


Related articles: