下面是一些工作中常用的的一些js方法,现对其进行些汇总,以方便日后查看:
//通用不带关闭提示框的浏览器窗口关闭方法
function CloseWin() { window.opener = null; //window.opener=top; window.open("", "_self"); window.close();}//只在一个新窗口打开链接function openOneWin(urlObj) {
window.open(urlObj.href, '1', ''); return false;}//在一个新窗口打开链接function openWin(url) {
window.open(url, '_blank', 'height=100, width=400, top=0, left=0, toolbar=no, menubar=no, scrollbars=no,resizable=no,location=no, status=no'); //height=100 窗口高度; //width=400 窗口宽度; //top=0 窗口距离屏幕上方的象素值; //left=0 窗口距离屏幕左侧的象素值; //toolbar=no 是否显示工具栏,yes为显示; //menubar,scrollbars 表示菜单栏和滚动栏。 //resizable=no 是否允许改变窗口大小,yes为允许; //location=no 是否显示地址栏,yes为允许; //status=no 是否显示状态栏内的信息(通常是文件已经打开),yes为允许;}
在iframe中关闭父窗体中的iframe
main.html
<html>
<head>
<title>主窗体</title>
<script type="text/javascript">
$(function(){
$("#btnOpen").click(function(){ // 在ifram中打开链接
openFrm(("div_mask","divContainer","");
});
$("#hidClose").click(function(){ // 关闭iframe窗体
closeFrm("div_mask","divContainer");
});
});
// 参数:0-遮罩层id;1-弹出层;2-url地址;3-iframe宽度;4-iframee高度;(高度和宽度参数为空)
function openFrm(maskId, divId, url, w, h) {
var _w = w || 300; // 默认宽高 var _h = h || 200; if ($("#" + divId + ">#myFrm").length == 0) { // iframe不存在则创建并添加到div容器 $("<iframe></iframe>").attr({ id: "myFrm", width: _w + "px", height: _h + "px", frameborder: "no", marginwidth: "0", marginheight: "0", scrolling: "yes", allowtransparency: "yes", border: "0" }
).appendTo($("#" + divId));
} document.getElementById("myFrm").src = url;changePopup(maskId, divId); // 设置弹层
}
// 参数:0-遮罩层id;1-弹出层
function closeFrm(maskId, divId) { $("#" + divId + ">iframe").remove(); // 移除iframechangePopup(maskId, divId); // 设置弹层
}
// 改变弹出层显示
function changePopup(maskId, divId) {
if ($('#' + maskId).css("display") == "none") {
var left = (document.body.scrollWidth - $('#' + divId).width()) / 2; var top = document.body.scrollTop + 100; $('#' + maskId).css({ display: "block" }); $('#' + divId).css({ display: "block", "left": left + "px", "top": top + "px" }); } else { $('#' + maskId).css({ display: "none" }); $('#' + divId).css({ display: "none" }); }}</script>
</head>
<body>
<div id="div_mask" class="popup_mask"> <!-- 遮罩层-->
</div><input type="button" id="btnOpen" value="打开链接" />
<input type="hidden" id="hidClose" /> <!-- 隐藏的关闭按钮-->
<div id='divContainer' class="popup_win"><!--弹出层,用于包含iframe的容器-->
</div>
</body>
</html>
child.html
<html>
<head>
<title>子窗体</title>
<script type="text/javascript">
$(function(){
$("#btnClose").click(function(){
// 触发父窗体按钮事件
window.parent.document.getElementById("hidClose").click();});
});
</head>
<body>
<input type="button" id="btnClose" value="关闭" />
<div><h1>我是子窗体</h1></div>
</body>
</html>
//全选\取消效果
function ckSelectAll(tblId, ckId) {//全选复选框点击事件
$("#" + ckId).click(function() { $("#" + tblId + " :checkbox:not([disabled])").attr("checked", this.checked); });}function ckSelect(tblId, ckId) {//单行复选框点击事件
$("#" + tblId + " :checkbox[id!='" + ckId + "']").each(function() {
$(this).click(function() { var flag = false; $("#" + tblId + " :checkbox[id!='" + ckId + "']").each(function() { if (!$(this).attr("checked")) { flag = true; } });if (flag) {
$("#" + ckId).attr("checked", false); } else { $("#" + ckId).attr("checked", true); } }); });}// 自动高度的文本框
function autoHeight(obj, default_height) {
var s_h = obj.scrollHeight; if (s_h > default_height) { obj.style.height = s_h + "px"; } else { obj.style.height = default_height + "px"; } }<textarea id="txt" style="height: 20px; overflow: hidden;" cols='20' οnkeyup="autoHeight(this,20);"></textarea>
//截取字符串function cutString(str, len) {
len=parseInt(len)*2;
var newLength = 0;
var newStr = ""; var chineseRegex = /[^\x00-\xff]/g; //匹配双字节字符,一个双字节字符长度计2,ASCII字符计1//var chineseRegex = new RegExp("^[\u0391-\uFFE5]$"); //区别:不匹配空格
var singleChar = ""; var strLength = str.length; for (var i = 0; i < strLength; i++) { singleChar = str.charAt(i).toString(); if (singleChar.match(chineseRegex) != null) { newLength += 2; } else { newLength++; } if (newLength > len) { break; } newStr += singleChar; } return newStr;}
//检查并设置元素value的最长度function checkMaxLength(o, maxlength) {
var cArr = o.value.match(/[^x00-xff]/g); // 匹配双字节字符,一个双字节字符长度计2,ASCII字符计1 var length = o.value.length + (cArr == null ? 0 : cArr.length);len=Math.ceil((length /2));
if (len > parseInt(maxlength)) {
//截取字符串
o.value = cutString(o.value, maxlength); }} // 更改可输入文字长度提示function changeAbleLengthTip(txtId, spanId, maxLen) { var cArr = $("#"+txtId).val().match(/[^x00-xff]/g); // 匹配双字节字符,一个双字节字符长度计2,ASCII字符计1 var length = obj.value.length + (cArr == null ? 0 : cArr.length); var len = length / 2; // 两个字节算一个长度 var ableLen = maxLen - Math.ceil(len); $("#" + spanId).text(ableLen.toString());}function getTextRealLength = function(txtId) {
var text = $("#" + txtId).val(); var charCode = null;var length = 0;
for (var i = 0; i < text.length; i++) { var j = text.charCodeAt(i); if (j > 127) { length += 1; } else { length += 0.5; } continue; } //计算出当前文本的长度 length = Math.ceil(length); return length; };
// 用正则表达式将前后空格,用空字符串替代。String.prototype.LTrim = function() {
return this.replace(/^[\s]+/g, "");}String.prototype.RTrim = function() { return this.replace(/[\s]+$/g, "");}String.prototype.Trim = function() {//return this.replace(/(^\s*)|(\s*$)/g, "");
return this.LTrim().RTrim();}
//提取html标签内容
String.prototype.replaceTag = function(tagName) {
if ((typeof tagName == "string") && (/^[a-zA-Z0-9]+$/.test(tagName))) {var reg = new RegExp("<" + tagName + "[^>]*>([^<]*)</" + tagName + ">", "gi");
return this.replace(reg, "$1"); //var reg1 = new RegExp("</?" + tagName + "[^>]*?>", "gi"); //return this.replace(reg1, ""); } else { return this; } }示例:
var str = "sd<a target='_selp'>1111</a>asff<a target='_selp'>2222</a><A>3333</A><h1>H1</h1>"; alert(str.replaceTag("a"));//输出:sd1111asff22223333><h1>H1</h1>//注意点:
//alert((typeof undefined)=="undefined"); // undefined,true
//alert((typeof null)=="object"); //object,true //alert(typeof "" == "string");//string,true //alert(typeof [] == "object"); //object,true //alert(typeof {} == "object"); //object,true
//提取A标签href
c#版:
Regex reg = new Regex(@"(?is)<a[^>]*?href=(['""]?)(?<url>[^'""\s>]+)\1[^>]*>(?<text>(?:(?!</?a\b).)*)</a>");Match m=reg.Match(html);
string url = m.Groups["url"].Value;
//获取页面地址传参
String.prototype.getQueryString = function(name) {
var reg = new RegExp("(^|&|\\?)" + name + "=([^&]*)(&|$)"), r; if (r = this.match(reg)) return unescape(r[2]); return null;};function getParameters() {
var str = location.search.substr(1) var reg = /([^&=]*)=([^&]*)(?=&|$)/g var arr; var results = new Array(); while (arr = reg.exec(str)) { results[arr[1]] = arr[2]; } return results;}function getSearchAsArray(srchStr) {
var results = new Array(); var input = unescape(srchStr.substr(1)); if (input) { var srchArray = input.split("&"); var tempArray = new Array(); for (var i = 0; i < srchArray.length; i++) { tempArray = srchArray[i].split("="); results[tempArray[0]] = tempArray[1]; } } return results;}function isUrl(str_url) {// 验证url
var strRegex = "^((https|http|ftp|rtsp|mms)?://)" + "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" // ftp的user@ + "(([0-9]{1,3}\.){3}[0-9]{1,3}" // IP形式的URL- 199.194.52.184 + "|" // 允许IP和DOMAIN(域名) + "([0-9a-z_!~*'()-]+\.)*" // 域名- www. + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." // 二级域名 + "[a-z]{2,6})" // first level domain- .com or .museum + "(:[0-9]{1,4})?" // 端口- :80 + "((/?)|" // a slash isn't required if there is no file name + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$"; var re = new RegExp(strRegex); return re.test(str_url); }
1.验证正负整数和小数
var reg =/^-?\d+(\.\d+)?$/;
2.验证中文
var reg = /[\u4E00-\u9FA5]/g;
3.验证时间
a)时分:
var regexObj = /^((2[0-3])|([0-1]?[0-9])):[0-5][0-9]$/;
var regexObj = /^(20|21|22|23|[0-1]?\d):[0-5]?\d$/;
b)年月日(含闰年闰月判断):
regexObj = /^((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-)) $/;
//滚动条滚动到底部事件
$("#div_scroll").css("height", $(window).height() - 150).scroll(function() {
var s_h = this.scrollHeight; // 滚动距离总长(注意不是滚动条的长度) var s_top = this.scrollTop; // 滚动到的当前位置 var h = $(this).height(); // div的高度 if (h + s_top == s_h) {// 滚动到底部时的事件处理
}
}
//获取时间戳
方法一:var timestamp = Date.parse(new Date()); // 把毫秒当成000显示
方法二:var timestamp = (new Date()).valueOf(); // 获取了当前毫秒的时间戳方法三:var timestamp = new Date().getTime(); // 获取了当前毫秒的时间戳
//时间添加
Date.prototype.addDays = function (number) {
if (!isNaN(number)) { var nowTime = this.getTime(); return new Date(nowTime + (number) * 24 * 60 * 60 * 1000); } else { return this; } };
//时间格式化
Date.prototype.format = function(format)
{ var o = { "M+" : this.getMonth()+1, //month "d+" : this.getDate(), //day "h+" : this.getHours(), //hour "m+" : this.getMinutes(), //minute "s+" : this.getSeconds(), //second "q+" : Math.floor((this.getMonth()+3)/3), //quarter "S" : this.getMilliseconds() //millisecond }; if("/(y+)/".test(format)) {format=format.replace(RegExp.$1,(this.getFullYear()+"").substr(4 - RegExp.$1.length));
}
for(var k in o){if(new RegExp("("+ k +")").test(format)){
format = format.replace(RegExp.$1,RegExp.$1.length==1 ? o[k] :("00"+ o[k]).substr((""+ o[k]).length));}
}
return format;}
json格式日期("/Date(1410019200000+0800)/")转换成js日期
function ConvertJsonDate(value)
{
return eval(value.replace(/\/Date\((\d+)\)\
//gi, "new Date($1)"));
}
// 页面隐藏js错误提示方法function killErrors() {
return true;}window.onerror =killErrors;