本系列文章旨在记录一些实用的javascript技巧,既可以作为一个知识的积累,又可以作为闲暇时打发时间写写代码的记录。同时也方便日后翻阅~
1. 操作DOM class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// 判断某个对象是否有指定的className function hasClass(ele,cls) { return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)')); } // 给指定对象添加className function addClass(ele,cls) { if (!this.hasClass(ele,cls)) ele.className += " "+cls; } // 删除className function removeClass(ele,cls) { if (hasClass(ele,cls)) { var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)'); ele.className=ele.className.replace(reg,' '); } } |
2. 分解url
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// 正则: /^([^:]+):\/\/(?:([^:@]+):?([^@]*)@)?(?:([^/?#:]+):?(\d*))([^?#]*)(?:\?([^#]+)?)?(?:#(.+)?)?$/ // 结果格式: Array [scheme] => http [host] => quchao.com [user] => user [pass] => pass [path] => /about-me [query] => t=100102 [fragment] => hash ) // demo: 'http://user:pass@xuanfenge.com:80/category/?s=css3#first' .match(/^([^:]+):\/\/(?:([^:@]+):?([^@]*)@)?(?:([^/?#:]+):?(\d*))([^?#]*)(?:\?([^#]+)?)?(?:#(.+)?)?$/); // 结果 ["http://user:pass@xuanfenge.com:80/category/?s=css3#first", "http", "user", "pass", "xuanfenge.com", "80", "/category/", "s=css3", "first"] |