MXOXW

Life always finds a way.

JavaScript常用函数汇总

| Comments

获取URL参数

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* 获取URL参数
* @param {[string]} name [description]
* @param {[string]} url [description]
* @return {[string]} [description]
*/
function getQuery(name, url) {
//参数:变量名,url为空则表从当前页面的url中取
var u = arguments[1] || window.location.search,
reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"),
r = u.substr(u.indexOf("\?") + 1).match(reg);
return r != null ? r[2] : "";
}

事件绑定

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* 事件绑定
*/
var EventUtil = {
addHandler: function( element, type, handler ) {
if ( element.addEventListener ) {
element.addEventListener ( type, handler, false );
} else if ( element.attachEvent ) {
element.attachEvent ( "on" + type, handler );
} else {
element["on" + type] = handler;
}
},

getEvent: function ( event ) {
return event ? event : window.event;
},

getTarget: function ( event ) {
return event.target || event.srcElement;
},

preventDefault: function ( event ) {
if ( event.preventDefault ) {
event.preventDefault();
} else {
event.returnValue = false;
}
},

removeHandler: function( element, type, handler ) {
if ( element.removeEventListener ) {
element.removeEventListener ( type, handler, false );
} else if ( element.detachEvent ) {
element.detachEvent ( "on" + type, handler );
} else {
element["on" + type] = null;
}
},

stopPropagation: function ( event ) {
if ( event.stopPropagation ) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
}

};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* 对象转为URL参数
* @param {[type]} param [description]
* @param {[type]} key [description]
* @return {[type]} [description]
*/
var parseParam = function(param, key) {
var paramStr = "";
if (param instanceof String || param instanceof Number || param instanceof Boolean) {
paramStr += "&" + key + "=" + encodeURIComponent(param);
} else {
$.each(param, function(i) {
var k = key == null ? i : key + (param instanceof Array ? "[" + i + "]" : "." + i);
paramStr += '&' + parseParam(this, k);
});
}
return paramStr.substr(1);
};

//调用:
var obj = {
name: 'tom',
'class': {
className: 'class1'
},
classMates: [{
name: 'lily'
}]
};
parseParam(obj);
结果: "name=tom&class.className=class1&classMates[0].name=lily"
parseParam(obj, 'stu');
结果: "stu.name=tom&stu.class.className=class1&stu.classMates[0].name=lily"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//替换url中指定参数
var replaceParam = function(param, value, url, forceReplace) {
url = url || location.href;
var reg = new RegExp("([\\?&]" + param + "=)[^&#]*"), hash = location.hash;
if (!url.match(reg)) {
if (!!hash) {
url = url.substring(0, url.indexOf('#'));
}
return ((url.indexOf("?") == -1) ? (url + "?" + param + "=" + value) : (url + "&" + param +
"=" + value)) + hash;
}
if (forceReplace) {
return url.replace(reg, "$1" + value);
}
return url;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//文字截断
function truncation() {
if (window.CSS && window.CSS.supports && window.CSS.supports('display', '-webkit-box')) {
return;
}

$('div span').each(function(index, el) {
var line = 0,
step, suffix = "...",
clientRects, isLimit = false,
string = this.innerHTML,
limit = 2; //限制行数

clientRects = this.getClientRects();
line = clientRects.length;

if (line <= limit) {
return;
}

while (line > limit) {
isLimit = true;
step = line > (limit + 1) ? 7 : 1;
string = string.substr(0, string.length - step);
this.innerHTML = string + suffix;
clientRects = this.getClientRects();
line = clientRects.length;
}
if (isLimit) {
string += suffix;
}
$(this).html(string);
});
}

JavaScript 权威指南-Window对象

| Comments

14.1 计时器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/*
* Schedule an invocation or invocations of f() in the future.
* Wait start milliseconds, then call f() every interval milliseconds,
* stopping after a total of start+end milliseconds.
* If interval is specified but end is omitted, then never stop invoking f.
* If interval and end are omitted, then just invoke f once after start ms.
* If only f is specified, behave as if start was 0.
* Note that the call to invoke() does not block: it returns right away.
*/
function invoke(f, start, interval, end) {
if (!start) start = 0; // Default to 0 ms
if (arguments.length <= 2) // Single-invocation case
setTimeout(f, start); // Single invocation after start ms.
else { // Multiple invocation case
setTimeout(repeat, start); // Repetitions begin in start ms
function repeat() { // Invoked by the timeout above
var h = setInterval(f, interval); // Invoke f every interval ms.
// And stop invoking after end ms, if end is defined
if (end) setTimeout(function() {
clearInterval(h);
}, end);
}
}
}

14.2 浏览器定位和导航
URL分解属性:protocol, host, hostname, port, pathname, search, hash

Extracting arguments from the search string of a URL

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*
* This function parses ampersand-separated name=value argument pairs from
* the query string of the URL. It stores the name=value pairs in
* properties of an object and returns that object. Use it like this:
*
* var args = urlArgs(); // Parse args from URL
* var q = args.q || ""; // Use argument, if defined, or a default value
* var n = args.n ? parseInt(args.n) : 10;
*/
function urlArgs() {
var args = {}; // Start with an empty object
var query = location.search.substring(1); // Get query string, minus '?'
var pairs = query.split("&"); // Split at ampersands
for (var i = 0; i < pairs.length; i++) { // For each fragment
var pos = pairs[i].indexOf('='); // Look for "name=value"
if (pos == -1) continue; // If not found, skip it
var name = pairs[i].substring(0, pos); // Extract the name
var value = pairs[i].substring(pos + 1); // Extract the value
value = decodeURIComponent(value); // Decode the value
args[name] = value; // Store as a property
}
return args; // Return the parsed arguments
}

14.2.2 载入新的文档
Location对象的assign()方法可以使窗口载入并显示你指定的URL中的文档。replace()方法也类似,但它在载入新文档之前会从浏览历史中把当前文档删除。如果脚本无条件地载入一个新文档,replace()方法可能是比assgin()方法更好的选择。否则,“后退”按钮会把浏览器带回到原始文档,而相同的脚本则会再次载入新文档。如果检测到用户
的浏览器不支持某些特性来显示功能齐全的版本,可以用location.replace()来载入静态的HTML版本。

1
2
3
4
5
6
7
location = "http://www.oreilly.com"; // Go buy some books!
location = "page2.html"; // Load the next page
/**
* #top不存在时,浏览器跳到文档开始处
*/
location = "#top"; // Jump to the top of the document
location.search = "?page=" + (pagenum+1); // load the next page

14.3 浏览历史

1
2
3
4
history.back();
history.forward();
history.go(0);
history.go(-2);

JavaScript 权威指南-Web浏览器中的JavaScript

| Comments

13.4.6 IE里的条件注释
HTML注释

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!--[if IE 6]>
This content is actually inside an HTML comment.
It will only be displayed in IE 6.
<![endif]-->
<!--[if lte IE 7]>
This content will only be displayed by IE 5, 6 and 7 and earlier.
lte stands for "less than or equal". You can also use "lt", "gt" and "gte".
<![endif]-->
<!--[if !IE]> <-->
This is normal HTML content, but IE will not display it
because of the comment above and the comment below.
<!--> <![endif]-->
This is normal content, displayed by all browsers.


<!--[if IE]><script src="excanvas.js"></script><![endif]-->

JavaScript注释
JScript是Microsoft的JavaScript解释器的名字, 而@_jscript变量在IE总是为true.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/*@cc_on
@if (@_jscript)
// This code is inside a JS comment but is executed in IE.
alert("In IE");
@end
@*/


/*@cc_on
@if (@_jscript)
// This code is inside a conditional comment, which is also a
// regular JavaScript comment. IE runs it but other browsers ignore it.
alert('You are using Internet Explorer);
@else*/
// This code is no longer inside a JavaScript comment, but is still
// inside the IE conditional comment. This means that all browsers
// except IE will run this code.
alert('You are not using Internet Explorer');
/*@end
@*/

13.6 安全性

同源策略
跨站脚本
拒绝服务攻击

JavaScript 权威指南-正则表达式

| Comments

10.2
"JavaScript".search(/script/i);
search()返回匹配的第一个子串的起始位置,找不到匹配的子串将返回-1。不支持全局检索。

replace()

1
2
// No matter how it is capitalized, replace it with the correct capitalization
text.replace(/javascript/gi, "JavaScript");