JS 模拟 POST 提交 (submit) 表单

function postcall( url, params, target){
	var tempform = document.createElement("form");
	tempform.action = url;
	tempform.method = "post";
	tempform.style.display="none"
	if(target) {
		tempform.target = target;
	}
	for (var x in params) {
		var opt = document.createElement("input");
		opt.name = x;
		opt.value = params[x];
		tempform.appendChild(opt);
	}
	var opt = document.createElement("input");
	opt.type = "submit";
	tempform.appendChild(opt);
	document.body.appendChild(tempform);
	tempform.submit();
	document.body.removeChild(tempform);
}

数组过滤重复值

//数组过滤重复值
function uniqueArr(array) {
  var n = []; //结果数组
  //从第一项开始遍历
  for (var i = 0; i < array.length; i++) {
	//如果当前数组的第i项在当前数组中第一次出现的位置不是i,
	//那么表示第i项是重复的,忽略掉。否则存入结果数组
	if (array.indexOf(array[i]) == i) n.push(array[i]);
  }
  return n;
}

删除空字符换行,过滤表格 text 中多余的空格

function Trim(str,is_global){
  var result;
  result = str.replace(/(^\s+)|(\s+$)/g,"");
  if(is_global && is_global.toLowerCase()=="g"){
	result = result.replace(/\s/g,"");
  }
  return result;
}

JS 中空的判断

alert(0 == ''); //true
alert(0 == false); //true
alert(false == ''); //true
alert(null == undefined); //true

alert(!0); //true
alert(!false); //true
alert(!undefined); //true
alert(!null); //true
alert(!''); //true

alert(0 == undefined); //false
alert(0 == null); //false
alert(false == null); //false
alert(false == undefined);//false
alert('' == null); //false
alert('' == undefined); //false

typeof(undefined) == 'undefined'
typeof(null) == 'object'
typeof("") == 'string'
typeof(0) == 'number'
typeof(false) == 'boolean'

String(undefined) -> "undefined"
String(null) -> "null"
String("") -> ""
String(0) -> "0"
String(false) -> "false"

区分 JS 中的 undefined , null , "" , 0 和 false

https://www.cnblogs.com/yangzhx/p/4019073.html

JS 移除 数组中指定元素

//首先需要找到元素的下标:
var array = [2, 5, 9];
var index = array.indexOf(5);
//使用splice函数进行移除:
if (index > -1) {
    array.splice(index, 1);
}
//splice函数的第二个参数指删除的数目。splice直接修改原数组,并把删除的所有元素以另一个新数组的方式返回。

数字前补零

function PrefixInteger(num, length) {
  return (Array(length).join('0') + num).slice(-length);
}

Toast 弹窗

function Toast(msg,duration){
  duration=isNaN(duration)?3000:duration;
  var m = document.createElement('div');
  m.innerHTML = msg;
  m.style.cssText="width: 60%;min-width: 150px;opacity: 0.7;height: 30px;color: rgb(255, 255, 255);line-height: 30px;text-align: center;border-radius: 5px;position: fixed;top: 40%;left: 20%;z-index: 999999;background: rgb(0, 0, 0);font-size: 12px;";
  document.body.appendChild(m);
  setTimeout(function() {
    var d = 0.5;
    m.style.webkitTransition = '-webkit-transform ' + d + 's ease-in, opacity ' + d + 's ease-in';
    m.style.opacity = '0';
    setTimeout(function() { document.body.removeChild(m) }, d * 1000);
  }, duration);
}

复制文本

//复制文本
function copy (id, attr='innerHTML') {
  let target = null;
  if (attr) {
    target = document.createElement('div');
    target.id = 'tempTarget';
    target.style.opacity = '0';
    if (id) {
      let curNode = document.querySelector('#' + id);
      target.innerText = curNode[attr];
    } else {
      target.innerText = attr;
    }
    document.body.appendChild(target);
  } else {
    target = document.querySelector('#' + id);
  }
  try {
    let range = document.createRange();
    range.selectNode(target);
    window.getSelection().removeAllRanges();
    window.getSelection().addRange(range);
    document.execCommand('copy');
    window.getSelection().removeAllRanges();
    console.log('复制成功:' + range)
  } catch (e) {
    console.log('复制失败')
  }
  if (attr) {
    // remove temp target
    target.parentElement.removeChild(target);
  }
}

获得链接地址的参数

function getQueryString(name,link=''){
  console.log(link)
  var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
  if(link){
    var num=link.indexOf("?");
    link=link.substr(num+1);
    var r = link.match(reg);
  }else{
    var r = window.location.search.substr(1).match(reg);
  }
  if(r!=null)return  unescape(r[2]); return null;
}

HTML 标签获取 图片地址

img_src: function (str){
  var imgReg = /<img.*?(?:>|\/>)/gi;
  var srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
  var arr = str.match(imgReg);    
  var list = []
  for(var i = 0; i < arr.length; i++) {
    var src = arr[i].match(srcReg);
    //获取图片地址
    if (src[1]) {
    list.push(src[1])
    }
    //当然你也可以替换src属性
    if (src[0]) {
      var t = src[0].replace(/src/i, "href");
    }
  }
  console.log(list)
  return list;
},

截取文件后缀

file_ext:function (name){
  let fileName = name.lastIndexOf(".");//取到文件名开始到最后一个点的长度
  let fileNameLength = name.length;//取到文件名长度
  let fileFormat = name.substring(fileName + 1, fileNameLength);//截
  console.log(fileFormat);
  return fileFormat
},

不刷新页面修改地址栏

var stateObject = {};
var title = "修改地址";
var newUrl = '/view/fontface4.html';
//修改地址栏中的地址,后退时返回当前页
history.pushState(stateObject, title, newUrl);
//修改地址栏中的地址,后退时返回前一页
history.replaceState(stateObject, title, newUrl);

jQuery Post 跳转

$.extend({
  StandardPost:function(url,args){
    console.log(args)
    var body = $(document.body),
      form = $("<form method='post'></form>"),
      input;
    form.attr({"action":url});
    $.each(args,function(key,value){
      input = $("<input type='hidden'>");
      input.attr({"name":key});
      input.val(value);
      form.append(input);
    });

    form.appendTo(document.body);
    form.submit();
    document.body.removeChild(form[0]);
  }
});
//使用
$.StandardPost(url,{data:'test'});

jQuery 模拟长按

$("#id").on({
  touchstart: function(e) {
    // 长按事件触发
    timeOutEvent = setTimeout(function() {
      timeOutEvent = 0;
      console.log("长按事件")
    }, 1000);
  },
  touchmove: function() {
    clearTimeout(timeOutEvent);
    timeOutEvent = 0;
  },
  touchend: function() {
    clearTimeout(timeOutEvent);
    timeOutEvent = 0;
    return false;
  }
})

指定日期的上个月,下个月

//下个月
const getNextMonth = function(date) {
  var arr = date.split('-');
  var year = arr[0]; //获取当前日期的年份
  var month = arr[1]; //获取当前日期的月份
  var day = arr[2]; //获取当前日期的日
  var days = new Date(year, month, 0);
  days = days.getDate(); //获取当前日期中的月的天数
  var year2 = year;
  var month2 = parseInt(month) + 1;
  if (month2 == 13) {
    year2 = parseInt(year2) + 1;
    month2 = 1;
  }
  var day2 = day;
  var days2 = new Date(year2, month2, 0);
  days2 = days2.getDate();
  if (day2 > days2) {
    day2 = days2;
  }
  if (month2 < 10) {
    month2 = '0' + month2;
  }

  var t2 = year2 + '-' + month2 + '-' + day2;
  return t2;
}
//上个月
const getPreMonth = function (date) {
  var arr = date.split('-');
  var year = arr[0]; //获取当前日期的年份
  var month = arr[1]; //获取当前日期的月份
  var day = arr[2]; //获取当前日期的日
  var days = new Date(year, month, 0);
  days = days.getDate(); //获取当前日期中月的天数
  var year2 = year;
  var month2 = parseInt(month) - 1;
  if (month2 == 0) {
    year2 = parseInt(year2) - 1;
    month2 = 12;
  }
  var day2 = day;
  var days2 = new Date(year2, month2, 0);
  days2 = days2.getDate();
  if (day2 > days2) {
    day2 = days2;
  }
  if (month2 < 10) {
    month2 = '0' + month2;
  }
  var t2 = year2 + '-' + month2 + '-' + day2;
  return t2;
}

HTML 锚点跳转平滑动画

    $('a[href*=#],area[href*=#]').click(function() {
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
            var $target = $(this.hash);
            $target = $target.length && $target || $('[name=' + this.hash.slice(1) + ']');
            if ($target.length) {
                var targetOffset = $target.offset().top;
                $('html,body').animate({
                        scrollTop: targetOffset
                    },
                    200);
                return false;
            }
        }
    });

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注