用apply让javascript函数仅执行一次的代码
代码如下:
var obj = new Object(); obj.triggerOnce = function(fn) { //控制让函数只触发一次 return function() { try { fn.apply(this, arguments); } catch (e) { var txt = "There was an error on this page.\n\n"; txt += "Error message: " + e.message + "\n\n"; txt += "Error name: " + e.name + "\n\n"; //alert(txt);//正式平台上可能需要注释掉该行 } finally { fn = null; } } }
调用形式:
代码如下:
function showMsg(arg){ alert(arg); } var fn=obj.triggerOnce(showMsg); fn(1);//只执行一次 fn(2);//没有调用fn
最后,关于javascript的apply方法,您可以简单参考这篇旧文。
【外一篇】用javascript取得querystring的值
在常见的网站中,经常碰到有“XXXX.aspx?username=jeffwong&address=北京” 这种形式的url,通过asp.net的Request对象获取键值轻而易举,通过js也不是很难,用下面的函数就可以搞定了:
代码
代码如下:
var urlStrs = location.search; //QueryString var Request = {}; Request.Count = 0; Request.Add = function(name, value) { if (Request.hasOwnProperty(name) == false) { Request.Count++; //如果不存在,计数添加1 } Request[name] = value; return true; } Request.QueryString = function(name) {//取对应的键值 var key = name.toString().toLocaleLowerCase(); //不区分大小写 var result = null; try { // if (Request.hasOwnProperty(key)) { result = Request[key]; // } } catch (e) { //alert(e.message); } return result; } Request.Init = function(urlQueryString) { if (urlQueryString.indexOf("?") != -1) { var url = urlQueryString.substr(1) var strArr = url.split("&"); for (var i = 0; i < strArr.length; i++) { var strChildArr = strArr[i].split("="); var name = String(strChildArr[0]).toLowerCase(); var value = unescape(strChildArr[1]); //unescape解码 this.Add(name, value); //添加 } } }
测试函数如下:
代码
代码如下:
//测试函数 function test() { Request.Init(urlStrs); //初始化request alert(Request.Count); var name = "username"; var value = Request.QueryString(name); alert(Request[name]); alert(Request.QueryString(name)); name = "address" alert(Request[name]); alert(Request.QueryString(name)); name = "age"; alert(Request[name]); alert(Request.QueryString(name)); }
需要说明的是,url里的参数通常都会有编码,本文采用的是比较常用的unescape进行解码,实际上,关于url参数编码,通常有escape,encodeURIComponent和encodeURI这三种编码函数,escape是window对象的内置函数,而另外两种则是javascript内置函数,它们解码的函数也是一一对应的关系(您可以参考这一篇),各自对应的反转函数分别是unescape,decodeURIComponent和decodeURI。
作者:Jeff Wong
相关推荐
softwear 2020-08-21
ZGCdemo 2020-08-16
northwindx 2020-05-31
zrtlin 2020-11-09
xuebingnan 2020-11-05
wikiwater 2020-10-27
heheeheh 2020-10-19
Crazyshark 2020-09-15
jczwilliam 2020-08-16
littleFatty 2020-08-16
idning 2020-08-03
jinxiutong 2020-07-26
lanzhusiyu 2020-07-19
Skyline 2020-07-04
xiaofanguan 2020-06-25
Aveiox 2020-06-23