Home Web Front-end JS Tutorial Summary of commonly used native js custom functions

Summary of commonly used native js custom functions

Dec 06, 2016 pm 01:36 PM
js

js gets the date function

   
//获取当前时间日期
function CurentTime()
{
  var now = new Date();
  var year = now.getFullYear();    //年
  var month = now.getMonth() + 1;   //月
  var day = now.getDate();      //日
  var hh = now.getHours();      //时
  var mm = now.getMinutes();     //分
  var clock = year + "-";
 
  if(month < 10)
    clock += "0";
 
  clock += month + "-";
 
  if(day < 10)
    clock += "0";
 
  clock += day + " ";
 
  if(hh < 10)
    clock += "0";
 
  clock += hh + ":";
  if (mm < 10) clock += &#39;0&#39;;
  clock += mm;
  return(clock);
}
Copy after login

js gets the time difference function

//获取时间差多少天
function getLastTime()
  {
    var startTime=new Date("1996-5-11 00:00"); //开始时间
    var endTime=new Date();  //结束时间
    var lastTime=endTime.getTime()-startTime.getTime() //时间差的毫秒数
 
    //计算出相差天数
    var days=Math.floor(lastTime/(24*3600*1000))
 
    //计算出小时数
    var leave1=lastTime%(24*3600*1000)  //计算天数后剩余的毫秒数
    var hours=Math.floor(leave1/(3600*1000))
    //计算相差分钟数
    var leave2=leave1%(3600*1000)    //计算小时数后剩余的毫秒数
    var minutes=Math.floor(leave2/(60*1000))
 
    //计算相差秒数
    var leave3=leave2%(60*1000)   //计算分钟数后剩余的毫秒数
    var seconds=Math.round(leave3/1000)
 
    return " 相差 "+days+"天 "+hours+"小时 "+minutes+" 分钟"+seconds+" 秒";
  }
Copy after login

js only automatically refreshes the page once

//自动刷新页面一次后停止刷新
window.onload = function(){
  if(location.search.indexOf("?")==-1){
   location.href += "?myurl";
  }
  else{
   if(location.search.indexOf("myurl")==-1) location.href += "&myurl";
  }
}
Copy after login

ajax instance

$.ajax({
    type: "POST",
    url: "join.php",
    data: dataString,
    success: function(){
      $(&#39;.success&#39;).fadeIn(200).show();
      $(&#39;.error&#39;).fadeOut(200).hide();
    }
  });
Copy after login

Get the window size in real time

$(window).resize(function(){
  var Height = $(window).height();
  var Width = $(window).width();
})
Copy after login

js loop execution function and timing execution function

//循环执行,每隔3秒钟执行一次showalert()
  window.setInterval(showalert, 3000);
  function showalert()
  {
    alert("循环执行");
  }
  //定时执行,5秒后执行show()
  window.setTimeout(show,5000);
   function show()
   {
 
    alert("定时执行");
   }
Copy after login

js get get parameter function

function GetQueryString(name)
{
   var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
   var r = window.location.search.substr(1).match(reg);
   if(r!=null)return unescape(r[2]); return null;
}
alert(GetQueryString("参数名1"));
Copy after login

js page printing array function

/**
 * 打印数组
 * @param {[type]} arr  要打印的数组
 * @param {[type]} space 控制打印的缩进
 * @param {[type]} space2 控制打印的缩进2
 */
 function print_arr(arr, space, space2)
 {
 
 space = space || &#39; &#39;;
 
 space2 = space2 || &#39;     &#39;;
 
 var str = "Array<br>"+space+"(<br>";
 
 for(var i=0; i<arr.length; i++)
 
 {
 
  if( Object.prototype.toString.call(arr[i]) == &#39;[object Array]&#39; )
 
  { //判断是否是数组,如果是,进行递归拼接
 
   str += space2 + &#39;[&#39; +i+"] => "+ print_arr(arr[i], space+&#39;   &#39;, space2+&#39;   &#39;);
 
  }
 
  else
 
  {
 
   str += space2 +&#39;[&#39;+i+"] => "+ arr[i] +"<br>";
 
  }
 
 }
 
 str += space+")<br>";
 
 document.write(str);
 
}
Copy after login

js prints json data into Array form output in html

/** 输出空格函数 */
function blank(num) {
 var res = &#39;&#39;;
 for (var i = 0; i < num; i++) {
  res += &#39; &#39;;
 }
 return res;
} 
 
/** 计算JSON对象数据个数 */
function jsonLen(jsonObj) {
 var length = 0;
 for (var item in jsonObj) {
    length++;
 }
 return length;
}
 
/** 解析JSON对象函数 */
function printObj(obj) {
 // JSON对象层级深度
 deep = (typeof(deep)==&#39;undefined&#39;) ? 0: deep;
 var html = "Array\n"; // 返回的HTML
 html += kong(deep) + "(\n";
 var i = 0;
 // JSON对象,不能使用.length获取数据的个数,故需自定义一个计算函数
 var len = typeof(obj) == &#39;array&#39; ? obj.length : jsonLen(obj);
 for(var key in obj){
  // 判断数据类型,如果是数组或对象,则进行递归
  // 判断object类型时,&&jsonLen(obj[key])是由于
  // 1、值(类似:email:)为null的时候,typeof(obj[key])会把这个key当做object类型
  // 2、值为null的来源是,数据库表中某些字段没有数据,查询之后直接转为JSON返回过来
  if(typeof(obj[key])==&#39;array&#39;|| (typeof(obj[key])==&#39;object&#39; && jsonLen(obj[key]) > 0) ){
   deep += 3;
   html += kong(deep) + &#39;[&#39; + key + &#39;] => &#39;;
   // 递归调用本函数
   html += printObj(obj[key],deep);
   deep -= 3;
  }else{
   html += kong(deep + 3) + &#39;[&#39; + key + &#39;] => &#39; + obj[key] + &#39;\n&#39;;
  }
  if (i == len -1) {
   html += kong(deep) + ")\n";
  };
  i++;
 }
 return html;
}
 
/** 向HTML页面追加打印JSON数据 */
function p_Obj(obj) {
 var div = document.getElementById(&#39;print-json-html&#39;);
 if (div != null) {
  document.body.removeChild(div);
 };
 var node = document.createElement("div");//创建一个div标签
 node.id = &#39;print-json-html&#39;;
 node.innerHTML = &#39;<pre class="brush:php;toolbar:false">&#39; + printObj(obj) + &#39;
'; document.body.appendChild(node); }
Copy after login

js prints the array length function of multi-dimensional array

//获取多维数组的数量
  function getArrNum(arr) {
 
    var eleNum = 0;
 
    if (arr == null) {
 
      return 0;
 
    }
 
    for (var i = 0; i < arr.length; i++) {
 
      for (var j = 0; j < arr[i].length; j++) {
 
        eleNum++;
 
      }
 
    }
 
    document.write(eleNum);
 
  }
Copy after login


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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use JS and Baidu Maps to implement map pan function How to use JS and Baidu Maps to implement map pan function Nov 21, 2023 am 10:00 AM

How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to create a stock candlestick chart using PHP and JS How to create a stock candlestick chart using PHP and JS Dec 17, 2023 am 08:08 AM

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

How to use JS and Baidu Maps to implement map heat map function How to use JS and Baidu Maps to implement map heat map function Nov 21, 2023 am 09:33 AM

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

How to use JS and Baidu Map to implement map click event processing function How to use JS and Baidu Map to implement map click event processing function Nov 21, 2023 am 11:11 AM

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

How to use JS and Baidu Maps to implement map polygon drawing function How to use JS and Baidu Maps to implement map polygon drawing function Nov 21, 2023 am 10:53 AM

How to use JS and Baidu Maps to implement map polygon drawing function. In modern web development, map applications have become one of the common functions. Drawing polygons on the map can help us mark specific areas for users to view and analyze. This article will introduce how to use JS and Baidu Map API to implement map polygon drawing function, and provide specific code examples. First, we need to introduce Baidu Map API. You can use the following code to import the JavaScript of Baidu Map API in an HTML file

See all articles