9个常用的javascript方法

版权声明:未经本人同意 ,不许转载文章,如果转载请备注链接地址! https://blog.csdn.net/qq_38366657/article/details/89533430

9个常用的javascript方法

//返回标签对象
function $(id) {
  return document.getElementById(id)
}
//清除空格
function trim(stringToTrim) {
  return stringToTrim.replace(/^\s+|\s+$/g, "")
}
//获取字符串二进制长度
function strLength(str) {
  var bytesCount = 0;
  for (var i = 0; i < str.length; i++) {
    var c = str.charAt(i);
    if (/^[\u0000-\u00ff]$/.test(c)) bytesCount += 1;
    else bytesCount += 2;
  }
  return bytesCount;
}
//设置cookie
function setCookie(name, value, minutes, path) {
  var expire = "";
  if (minutes != null) {
    expire = new Date((new Date()).getTime() + minutes * 60000);
    expire = ";expires=" + expire.toGMTString();
  }
  document.cookie = name + "=" + escape(value) + expire + ((path) ? ";path=" + path: "");
}
//获取cookie
function getCookie(name) {
  var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
  if (arr != null) return unescape(arr[2]);
  return null;
}
//添加收藏夹
function addfav() {
  try {
    if (document.all) {
      window.external.addFavorite(location.href, document.title);
    } else {
      window.sidebar.addPanel(document.title, window.location.href, "");
    }
  } catch(e) {
    alert("加入收藏失败,请使用Ctrl+D进行添加")
  }
}
//获取网页参数
function getQueryString(name) {
  var re = new RegExp("[&,?]" + name + "=([^\\&]*)", "i");
  var r = re.exec(document.location.search);
  if (r != null) return unescape(r[1]);
  return null;
}
//判断输入情况,公用 id:对象,str对象名称
function showAlert(id, str) {
  if (trim($(id).value) == "") {
    alert(str + "不能为空,请输入" + str + "!");
    $(id).focus();
    return false;
  }
  return true;
}
//比较两个对象的值
function Compare(id1, id2, str) {
  if (parseInt($(id2).value, 10) < parseInt($(id1).value, 10)) {
    alert(str);
    $(id2).focus();
    return false;
  }
  return true;
}

猜你喜欢

转载自blog.csdn.net/qq_38366657/article/details/89533430