Home > Web Front-end > JS Tutorial > Some more practical js methods_javascript skills

Some more practical js methods_javascript skills

WBOY
Release: 2016-05-16 15:04:44
Original
1334 people have browsed it

This article shares some of the more practical js methods that I have accumulated in my daily life for your guidance and evaluation. I wanted to introduce it in parts, but found that it was a bit superfluous. After sorting it out, there are not many practical methods. Naturally, there are some methods that I have seen on the Internet that I think are very practical. I will post them here for everyone to discuss.

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

First of all, there is a requirement in the customer demand - a single page shared to WeChat, click Return to jump to the homepage of the website.

During this period, we discussed this function with our customers, whether we can add a return to home page button to jump to the page.

However, this method cannot be applied to every page, and the sharing page that requires this function cannot place an icon without affecting the aesthetics. So, I had no choice but to pursue Du Niang. Du Niang is also full of marginal functions.

So through my own attempts, I have the following code:

//返回之前没页面则返回首页
function pushHistory() {
  //获取浏览器历史记录栈中的记录个数
  //由于页面加载的时候就会将当前页面压入栈中 所以判断是否小于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", "");
  }
}
Copy after login

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

Copy after login

The specific function is to determine whether there is a page before. If not, insert the link address of the specified website into the state (the homepage is used here), and then listen to the popstate event and perform the corresponding function operations.

This code may still have some minor problems, so I plan to post it so that someone can discuss and improve it together.

2. Convenient log method

I believe that everyone is already tired of the slightly lengthy typing length of console.log() when debugging the page. Some people may use shortcut input for quick input (for example: enter cl to intelligently pop up the console in the compilation environment). However, when the project is released, it will still be difficult to clear out a lot of debugging information that I forgot to delete. So I simply wrote a method to deal with this situation specifically.

function lll() {
  //全局变量_debug用来控制调试信息开关
  if (_debug) {
    var arr = [];
    //arguments是方法的参数集合 这样做是为了不限制参数的个数,方便调试
    for (_item in arguments) {
      //由于个人习惯字符串信息就显示在一行里所以对字符串进行了筛选拼接
      if (typeof _item == "String") {
        arr.push(_item)
      } else {
        console.log(_item)
      }
    }
    if(arr.length>0)console.log(arr.join(','))
  }
}
Copy after login

In fact, what I am a little dissatisfied about is that there is no way to automatically obtain the name of the parameter, otherwise it can be used like this:

var a = 123, b = 333, obj = { name: "name", content: "..." }
 lll(a, b, obj)//调试信息为: a:123,b:123
        //obj:
        //{ name: "name", content: "..." }
Copy after login

Does it seem more clear?

3. Obtain browser positioning information (supports mobile)

Many projects received are customized and developed for mobile terminals, so information that needs to locate the current location is often used.

But many interfaces on the Internet need to reference a piece of external js, such as Baidu’s API, WeChat’s API, etc.

Next, I will introduce a method that does not require referencing external js, but only requires submitting parameters to the external API link to obtain positioning:

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

    if (navigator.userAgent.indexOf("MicroMessenger") > -1) {//判断是否是微信端,具体视情况而定
      navigator.geolocation.getCurrentPosition(function getPositionSuccess(position) {
        //通过html5的navigator.geolocation接口 获取浏览器的当前定位 (移动端最准确,PC会有较大偏差)
        var lat = position.coords.latitude;//获取过来的当前纬度
        var lng = position.coords.longitude;//获取过来的当前经度
        var arr = []
        arr.push(lng)
        arr.push(lat)
        //alert(position)
        $.ajax({
          type: "GET",
          url: "http://api.map.baidu.com/geocoder/v2/&#63;ak=oM55dVWVwLUU7shkz7uY8M6E&callback=renderReverse&location=" + lat + "," + lng + "&output=json&pois=1",//将经纬度通过地址栏参数的形式 传给百度提供的api
          beforeSend: function () {
            //由于这段过程需要些时间 所以最好页面上有加载提示
            iosload()//本人写的页面加载动画
          },
          data: {},
          dataType: "jsonp",//由于是跨域传输 所以需要以jsonp的形式进行传输
          jsonpCallback: "renderReverse",//类似跨域传输的标识 需要接收方和传输方做好统一
          success: function (data) {
            ios.hide();
            //alert(data)
            $("#myposition").html("我在:" + data.result.addressComponent.city)
            setCookie("position", data.result.addressComponent.city, 24 * 60 * 30)
          }
        })

  }, function (error) {
    //alert(error.message);
  }, {})
  }
}

Copy after login

This code is a piece of code in my actual project. Since I need to determine whether the positioning information has been obtained, I cannot obtain it every time the page is loaded, so I use Cookie to save the positioning information

At the beginning, it was judged whether there was a current positioning information cookie, but there was no. Then determine whether it is on the mobile side (because the project is on the WeChat side, so I only verified it on the WeChat side)

Then call the interface parameters provided by html5 for data transmission, and process the jsonp returned by Baidu. Since I only need to obtain the location city information in my project, here is just an example of obtaining the city.

4. Get the numerical part of the string

Since I am only responsible for the implementation of functions in the project, many pages are not built by me, but some novices will create some situations where it is difficult to obtain the values ​​​​in the tags.

For example:

<div>原价998现在只要
  <a>99.8!</a>
 </div>
Copy after login

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

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);
 }
Copy after login

This method is very short, and it is essentially matching through regular expressions. Replace non-digit or decimal point characters with empty strings (actually delete them)

The data returned in this way is the number we want. I finally performed a conversion operation to floating point type. This is to facilitate the post-processing of the data. For example, retaining two decimal places, rounding, etc.

5. Obtain device information

//#region 获取设备信息

var browser = {
  versions: function () {
    var u = navigator.userAgent, app = navigator.appVersion;
    return {
      trident: u.indexOf('Trident') > -1, //IE内核
      presto: u.indexOf('Presto') > -1, //opera内核
      webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
      gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,//火狐内核
      mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
      ios: !!u.match(/\(i[^;]+;( U;)&#63; CPU.+Mac OS X/), //ios终端
      android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
      iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
      iPad: u.indexOf('iPad') > -1, //是否iPad
      webApp: u.indexOf('Safari') == -1, //是否web应该程序,没有头部与底部
      weixin: u.indexOf('MicroMessenger') > -1, //是否微信 (2015-01-22新增)
      qq: u.match(/\sQQ/i) == " qq" //是否QQ
    };
  }(),
  language: (navigator.browserLanguage || navigator.language).toLowerCase()
}

//实际使用的时候如下:
if (browser.versions.webKit) {
  //为苹果 谷歌内核执行的代码...
}

//#endregion

Copy after login

Here I also share a way of judging device information that is encapsulated into an object and was not written by me but also seen on the Internet.

I personally think it’s very useful, so I’ll share it with everyone.

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

1. Hide the part of the string that exceeds the specified length

/*
将字符串以指定长度显示,多余部分以省略号显示(len--显示长度
defaultStr--若字符串为空显示的字符串)
*/
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;
}
Copy after login

Annotations are simple and clear enough. If you don’t understand, you can leave a message, and the blogger will definitely reply after seeing it.

2. Decrease the length of the string by one

//长度减一
 String.prototype.delLast = function () {
   return this.substring(0, this.length - 1)
 }
Copy after login

有些人可能会觉得 这个方法有点脱裤子放屁的嫌疑,其实真正的项目中 会经常需要这个操作。

与其写一段长长的substring 不如咱们写个方法将代码精简,并且在码代码的时候 也很方便 直接在对应的字符串后面 轻轻一点,选择delLast就行。

一句话,用过都说好!

3.将数字型字符串补全指定长度

//给数字型字符串固定指定长度
String.prototype.addZero = function (n) {
  var num = this
  var len = num.toString().length;
  while (len < n) {
    num = '0' + num;
    len++;
  }
  return num;
}
Copy after login

看注释可能有点不理解 其实就是加入这个字符串是 "2",通过这个扩展方法 可以这么操作 "2".addZero(2)

那么返回过来的就是"02"这样的字符串。

用过都说好!

4.将数据库DateTime类型转换为Date

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

5.用户昵称省略 

//用户昵称省略
 String.prototype.telHide = function () {
   var name = this
   return name.substr(0, 1) + "****" + name.substring(name.length - 1, name.length)
 }
Copy after login

以上就是本文的全部内容,希望对大家的学习有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template