特别板块:js跨域请求Tomcat6、tomcat7 跨域设置(包含html5 的CORS)

需要下载两个jar文件,cors-filter-1.7.jar,Java-property-utils-1.9.jar这两个库文件,http://download.csdn.net/detail/csr0312/9280097 
放到tomcat lib目录下面,不是项目的lib目录,然后配置项目的web.xml,添加如下内容,注意filter位置,应该放在第一位

  1. <!-- 实现跨域 -->
  2. <filter>
  3. <filter-name>CORS</filter-name>
  4. <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
  5. <init-param><!-- 一般为了安全考虑会指定具体几个地址源 -->
  6. <param-name>cors.allowOrigin</param-name>
  7. <param-value>*</param-value>
  8. </init-param>
  9. <init-param>
  10. <param-name>cors.supportedMethods</param-name>
  11. <param-value>GET, POST, HEAD, PUT, DELETE</param-value>
  12. </init-param>
  13. <init-param><!-- 消息头设置 -->
  14. <param-name>cors.supportedHeaders</param-name>
  15. <param-value>Accept, Origin, X-Requested-With, Content-Type, Last-Modified,Access-Control-Allow-Origin</param-value>
  16. </init-param>
  17. <init-param>
  18. <param-name>cors.exposedHeaders</param-name>
  19. <param-value>Set-Cookie</param-value>
  20. </init-param>
  21. <init-param>
  22. <param-name>cors.supportsCredentials</param-name>
  23. <param-value>true</param-value>
  24. </init-param>
  25. </filter>
  26. <filter-mapping>
  27. <filter-name>CORS</filter-name>
  28. <url-pattern>/*</url-pattern>
  29. </filter-mapping>

0、js版本检测

  1. <html>
  2. <head>
  3. <title>JavaScript版本测试</title>
  4. </head>
  5. <body>
  6. <script language="JavaScript">
  7. //仅支持JavaScript 1.0的浏览器才读该部分
  8. document.write('浏览器支持JavaScript 1.0<br>');
  9. </script>
  10. <script language="JavaScript1.1">
  11. //仅支持JavaScript 1.1的浏览器才读该部分
  12. document.write('浏览器支持JavaScript 1.1<br>');
  13. </script>
  14. <script language="JavaScript1.2">
  15. //仅支持JavaScript 1.2的浏览器才读该部分
  16. document.write('浏览器支持JavaScript 1.2<br>');
  17. </script>
  18. <script language="JavaScript1.3">
  19. //仅支持JavaScript 1.3的浏览器才读该部分
  20. document.write('浏览器支持JavaScript 1.3<br>');
  21. </script>
  22. <script language="JavaScript1.4">
  23. //仅支持JavaScript 1.4的浏览器才读该部分
  24. document.write('浏览器支持JavaScript 1.4<br>');
  25. </script>
  26. <script language="JavaScript1.5">
  27. //仅支持JavaScript 1.5的浏览器才读该部分
  28. document.write('浏览器支持JavaScript 1.5<br>');
  29. </script>
  30. <script language="JavaScript1.6">
  31. //仅支持JavaScript 1.6的浏览器才读该部分
  32. document.write('浏览器支持JavaScript 1.6<br>');
  33. </script>
  34. <script language="JavaScript1.7">
  35. //仅支持JavaScript 1.7的浏览器才读该部分
  36. document.write('浏览器支持JavaScript 1.7<br>');
  37. </script>
  38. <script language="JavaScript1.8">
  39. //仅支持JavaScript 1.8的浏览器才读该部分
  40. document.write('浏览器支持JavaScript 1.8<br>');
  41. </script>
  42. <script language="JavaScript1.9">
  43. //仅支持JavaScript 1.9的浏览器才读该部分
  44. document.write('浏览器支持JavaScript 1.9<br>');
  45. </script>
  46. </body>
  47. </html>

1、trigger

  情景:在项目中,tab页切换时,元素无法正常显示出来,拖动窗口大小时,又能正常显示;

  可在tab的切换点击事件中加入该操作:

  $(window).trigger("resize",$(window).width(),$(window).height()); 即重置窗口大小,实现拖动窗口效果。

2、$.attr()问题:

  情景:<input id="tt" clickEvent="sendInfo('info')"> ,

       $("#tt").attr("clickEvent") 结果取出来的是“sendInfo(”,

     因为该代码经过浏览器解析后,变成<input id='tt' clickEvent='sendInfo('info')'>,故有此结果;

       如果属性是通过后台拼接,该问题更突出(如:java中的标签)。

  处理方法:1、改写成:<input id="tt" clickEvent='sendInfo("info")'>

       2、案例:

        字符串1:{"cityId":"110100","cityName":"北京市辖区"}

        字符串2:{&quot;cityId&quot;:&quot;110100&quot;,&quot;cityName&quot;:&quot;北京市辖区&quot;}

        如上字符串所示,字符串1是在java后台生成,通过structs2传递到前台后,js中取得的字符串却变成了字符串2的样子,

        其中的”变成了&quot;使用的时候用StringEscapeUtils.unescapeHtml(字符串2)) 解下码就行,便可取得原字符串1。

        由以上可以找到解决方案:

          1、后台传前台:[如json字符串].replaceAll("[\"']", "&quot;"),先将字符串中的单引号和双引号转出"&quot;",

             传到前台后浏览器会自动解析格式;

          2、前台传后台:都是自己写的,这个就不要偷懒啦,注意下格式就行了。

3、jquery简雅之美:

  1)、简雅之美 - 高兼容事件绑定

    比如input的值改变事件,正常我们可能都会想到onpropertychange事件,于是这样操作:

    $(ob).bind("propertychange",function(){ ...... });

    但是问题又来了,onpropertychange事件是ie专有的,可恶的是还只是ie9一下的版本才能有效;

    那ie9及以上版本咋整?不急还有oninput事件,于是写下如下代码:

    $(ob).bind("input",function(){ ...... });

    然这样并没有解决问题,这种照顾了ie9及以上版本却照顾不了ie8等低版本,不急我们可以这样写:

    $(ob).bind("input propertychange",function(){ ...... });于是问题解决了。

    绑定事件如此写,其实可以看成是事件选择器,既优雅又简洁。

4、js判断输入字符串长度(汉字算两个字符,字母数字算一个)

  汉字在数据库中占2个字符,如果输入字符超过数据库表字段长度,会出现错误,因此需要在前台进行判断。有两种方法进行判断:

方法一:使用正则表达式,代码如下:

  1. function getByteLen(val) {
  2.  
  3. var len = 0;
  4.  
  5. for (var i = 0; i < val.length; i++) {
  6.  
  7. var a = val.charAt(i);
  8.  
  9. if (a.match(/[^\x00-\xff]/ig) != null) {
  10.  
  11. len += 2;
  12.  
  13. } else {
  14.  
  15. len += 1;
  16.  
  17. }
  18.  
  19. }
  20.  
  21. return len;
  22.  
  23. }

方法二:使用字符unicode判断:方法如下:

  1. function getByteLen(val) {
  2.  
  3. var len = 0;
  4.  
  5. for (var i = 0; i < val.length; i++) {
  6.  
  7. var length = val.charCodeAt(i);
  8.  
  9. if(length>=0&&length<=128) {
  10.  
  11. len += 1;
  12.  
  13. } else {
  14.  
  15. len += 2;
  16.  
  17. }
  18.  
  19. }
  20.  
  21. return len;
  22.  
  23. }

5、比较完美的日期格式化

  a、(如jsp)头部引入标签<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

  b、利用<fmt:formatDate value="${obj.date}" pattern="yyyy-M-d" />嵌套到要初始化的输入域:

    <input type="text" value="<fmt:formatDate value="${obj.date}" pattern="yyyy-M-d" />"/>

 js之字符串转日期:建议使用  'yyyy/MM/dd' 格式,'yyyy-MM-dd' 这种格式在ie9以下时容易出现NoN解析异常

  即:var date1 = new Date('2016/01/01'); (兼容性好)

    var date2 = new Date('2016-01-01'); (ie9以下易出问题)

  如果非要出入'yyyy-MM-dd' 格式,如下处理

    dateStr = '2016-01-01';

    var date2 = new Date(Date.parse(dateStr.replace(/-/g,   "/")));

6、调用iframe里的js函数 
  如: document.getElementById('iframedemo').targetfunction(); 
  但是这段代码在firefox下报错,于是上google搜索,发现一个解决办法,在ie和firefox 下均工作正常,代码如下: 
  document.getElementById('iframedemo').contentWindow.demofunction(); 
  其中iframedemo是iframe的id

7、纯js事件追加之window.addEventListener

  window.addEventListener('resize',method1);

  window.addEventListener('resize',method2);

  window.addEventListener('resize',method3);

  执行顺序为:method1 -> method2 -> method3

  例如图表插件Echarts在setoption之后添加这段代码:

  1. window.addEventListener('resize', function () {

  myChart.resize();
   });

图表就能随着窗口大小,自动适应,且支持一页多图。

8、监测js加载

场景:项目中监测js或者css是否重复加载,避免冗余请求,减轻后端压力

  1. <!-- Bootstrap core JavaScript -->
  2. <script src="/js/jquery/jquery-1.8.3.min.js"></script>
  3. <script src="/js/bootstrap/js/bootstrap.min.js"></script>
  4. <script src="/js/framework/jquery.menu.js"></script>
  5. <script src="/js/framework/jquery.menu.js"></script>
  6. <script src="/portal/common/js/jquery-easyui/jquery.easyui.min.js"></script>
  7. <script type="text/javascript">
  8. var msg = [];
  9. $("script").each(function(){
  10.   var item = $(this);
  11.   $("script").each(function(){
  12.     var innerItem = $(this);
  13.     if(item.attr("src")==innerItem.attr("src")){
  14.       var count = $("script[src*='"+item.attr("src")+"']").size() || 0;
  15.       if(count>1){
  16.         var itemInfo = item.attr("src")+":"+count+"\n";
  17.         if($.inArray(itemInfo,msg)<0){
  18.           msg.push(itemInfo);
  19.         }
  20.       }
  21.     }
  22.   });
  23. });
  24. if(msg!=""){
  25.   $.messager.alert("提示",msg);
  26. }
  27. </script>

输出结果:/js/framework/jquery.menu.js:2

9、form表单提交巧技 -- post传参方式打开新窗口

  1. // 打开新窗口post方式提交,target是关键
  2. function submitForm(url,param){
  3. var form = $("<form anction='"+url+"' method='post' target='_blank' style='width: 0px;height: 0px;'></form>").appendTo(document.body);
  4. for(var item in subParam){
  5. var input = $("<input type='hidden' name='"+item+"' value='"+param[item]+"'/>");
  6. form.append(input);
  7. }
  8. form.submit();
  9. form.remove();
  10. }

这样封装之后,是不是超好用捏O(∩_∩)O

10、js函数类Math之最大值max和最小值min

  1. var a=[1,2,3,5];
  2. alert(Math.max.apply(null, a));//最大值
  3. alert(Math.min.apply(null, a));//最小值
  4.  
  5. 多维数组
  6. var a=[1,2,3,[5,6],[1,4,8]];
  7. var ta=a.join(",").split(",");//转化为一维数组
  8. alert(Math.max.apply(null,ta));//最大值
  9. alert(Math.min.apply(null,ta));//最小值
  10.  
  11. 使用链式
  12. Array.prototype.max = function() {
  13. return Math.max.apply({},this)
  14.  
  15. }
  16. Array.prototype.min = function() {
  17. return Math.min.apply({},this)
  18.  
  19. }
  20. [1, 2, 3].max()// => 3
  21. [1, 2, 3].min()// => 1
  22.  
  23. 使用方法[1,2,3].max()
  24. Array.max = function(array) {
  25. return Math.max.apply(Math, array);
  26.  
  27. };
  28.  
  29. Array.min = function(array) {
  30. return Math.min.apply(Math, array);
  31.  
  32. };

11、js之apply和call方法详解

  1. js applyjs call方法总是让初学者困惑,下文就applycall的区别,什么情况下用apply,什么情况下用callapply的巧妙用法来阐述js applyjs call方法的详细使用方法。
  2.  
  3. 主要我是要解决一下几个问题:
  4.  
  5. 1. applycall的区别在哪里
  6.  
  7. 2. 什么情况下用apply,什么情况下用call
  8.  
  9. 3. apply的其他巧妙用法(一般在什么情况下可以使用apply
  10.  
  11. apply:方法能劫持另外一个对象的方法,继承另外一个对象的属性.
  12.  
  13. Function.apply(obj,args)方法能接收两个参数:
  14.  
  15. obj:这个对象将代替Function类里this对象
  16. args:这个是数组,它将作为参数传给Functionargs-->arguments
  17.  
  18. call:和apply的意思一样,只不过是参数列表不一样.
  19.  
  20. Function.call(obj,[param1[,param2[,…[,paramN]]]])
  21.  
  22. obj:这个对象将代替Function类里this对象
  23. params:这个是一个参数列表
  24.  
  25. 1. apply示例:
  26.  
  27. js applyjs call方法详解
  28.  
  29. 分析: Person.apply(this,arguments);
  30.  
  31. this:在创建对象在这个时候代表的是student
  32.  
  33. arguments:是一个数组,也就是[“zhangsan”,”21”,”一年级”];
  34.  
  35. 也就是通俗一点讲就是:用student去执行Person这个类里面的内容,在Person这个类里面存在this.name等之类的语句,这样就将属性创建到了student对象里面
  36.  
  37. 2. call示例
  38.  
  39. Studen函数里面可以将apply中修改成如下:
  40.  
  41. Person.call(this,name,age);
  42.  
  43. 这样就ok
  44.  
  45. 3.什么情况下用apply,什么情况下用call
  46.  
  47. 在给对象参数的情况下,如果参数的形式是数组的时候,比如apply示例里面传递了参数arguments,这个参数是数组类型,并且在调用Person的时候参数的列表是对应一致的(也就是PersonStudent的参数列表前两位是一致的) 就可以采用 apply , 如果我的Person的参数列表是这样的(age,name),而Student的参数列表是(name,age,grade),这样就可以用call来实现了,也就是直接指定参数列表对应值的位置(Person.call(this,age,name,grade));
  48.  
  49. 4. apply的一些其他巧妙用法
  50.  
  51. 细心的人可能已经察觉到,在我调用apply方法的时候,第一个参数是对象(this), 第二个参数是一个数组集合, 在调用Person的时候,他需要的不是一个数组,但是为什么他给我一个数组我仍然可以将数组解析为一个一个的参数,这个就是apply的一个巧妙的用处,可以将一个数组默认的转换为一个参数列表([param1,param2,param3] 转换为 param1,param2,param3) 这个如果让我们用程序来实现将数组的每一个项,来装换为参数的列表,可能都得费一会功夫,借助apply的这点特性,所以就有了以下高效率的方法:
  52.  
  53. a) Math.max 可以实现得到数组中最大的一项
  54.  
  55. 因为Math.max 参数里面不支持Math.max([param1,param2]) 也就是数组
  56.  
  57. 但是它支持Math.max(param1,param2,param3…),所以可以根据刚才apply的那个特点来解决 var max=Math.max.apply(null,array),这样轻易的可以得到一个数组中最大的一项(apply会将一个数组装换为一个参数接一个参数的传递给方法)
  58.  
  59. 这块在调用的时候第一个参数给了一个null,这个是因为没有对象去调用这个方法,我只需要用这个方法帮我运算,得到返回的结果就行,.所以直接传递了一个null过去
  60.  
  61. b) Math.min 可以实现得到数组中最小的一项
  62.  
  63. 同样和 max是一个思想 var min=Math.min.apply(null,array);
  64.  
  65. c) Array.prototype.push 可以实现两个数组合并
  66.  
  67. 同样push方法没有提供push一个数组,但是它提供了push(param1,param,…paramN) 所以同样也可以通过apply来装换一下这个数组,即:
  68.  
  69. vararr1=new Array("1","2","3");
  70. vararr2=new Array("4","5","6");
  71. Array.prototype.push.apply(arr1,arr2);
  72. 也可以这样理解,arr1调用了push方法,参数是通过apply将数组装换为参数列表的集合.
  73.  
  74. 通常在什么情况下,可以使用apply类似Math.min等之类的特殊用法:
  75.  
  76. 一般在目标函数只需要n个参数列表,而不接收一个数组的形式([param1[,param2[,…[,paramN]]]]),可以通过apply的方式巧妙地解决这个问题!

12、Map扩展

Map对象在ie下,是有兼容性问题的,ie9+才好使,为此只能扩展Map了

  1. (function(win) {
  2. var Map = function() {
  3. this.count = 0;
  4. this.entrySet = {};
  5. };
  6.  
  7. var proto = Map.prototype;
  8.  
  9. proto.size = function() {
  10. return this.count;
  11. };
  12.  
  13. proto.isEmpty = function() {
  14. return this.count == 0;
  15. };
  16.  
  17. proto.containsKey = function(key) {
  18. if (this.isEmpty()) {
  19. return false;
  20. }
  21. for ( var prop in this.entrySet) {
  22. if (prop == key) {
  23. return true;
  24. }
  25. }
  26.  
  27. return false;
  28. };
  29.  
  30. proto.containsValue = function(value) {
  31. if (this.isEmpty()) {
  32. return false;
  33. }
  34.  
  35. for ( var key in this.entrySet) {
  36. if (this.entrySet[key] == value) {
  37. return true;
  38. }
  39. }
  40.  
  41. return false;
  42. };
  43.  
  44. proto.get = function(key) {
  45. if (this.isEmpty()) {
  46. return null;
  47. }
  48.  
  49. if (this.containsKey(key)) {
  50. return this.entrySet[key];
  51. }
  52.  
  53. return null;
  54. };
  55.  
  56. proto.put = function(key, value) {
  57. this.entrySet[key] = value;
  58. this.count++;
  59. };
  60.  
  61. proto.remove = function(key) {
  62. if (this.containsKey(key)) {
  63. delete this.entrySet[key];
  64. this.count--;
  65. }
  66. };
  67.  
  68. proto.putAll = function(map) {
  69.      if(!map instanceof Map){
  70.        return;
  71.      }
  72.  
  73. for ( var key in map.entrySet) {
  74. this.put(key, map.entrySet[key]);
  75. }
  76. };
  77.  
  78. proto.clear = function() {
  79. for ( var key in this.entrySet) {
  80. this.remove(key);
  81. }
  82. };
  83.  
  84. proto.values = function() {
  85. var result = [];
  86.  
  87. for ( var key in this.entrySet) {
  88. result.push(this.entrySet[key]);
  89. }
  90.  
  91. return result;
  92. };
  93.  
  94. proto.keySet = function() {
  95. var result = [];
  96.  
  97. for ( var key in this.entrySet) {
  98. result.push(key);
  99. }
  100.  
  101. return result;
  102. };
  103.  
  104. proto.toString = function() {
  105. var result = [];
  106. for ( var key in this.entrySet) {
  107. result.push(key + ":" + this.entrySet[key]);
  108. }
  109.  
  110. return "{" + result.join() + "}";
  111. };
  112.  
  113. proto.valueOf = function() {
  114. return this.toString();
  115. };
  116.  
  117. win.Map = Map;
  118. })(window);

13、JSON.stringify()兼容扩展

源码:https://github.com/douglascrockford/JSON-js

这个JS中的函数将JSON对象转换成JSON字符串,解决 IE6、7、8不能使用 JSON.stringify 函数的问题!

  1. <!--[if lt IE 9]>
  2. <script src="json2.js"></script>
  3. <![endif]-->
  1. // json2.js
  2. // 2016-05-01
  3. // Public Domain.
  4. // NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
  5. // See http://www.JSON.org/js.html
  6. // This code should be minified before deployment.
  7. // See http://javascript.crockford.com/jsmin.html
  8.  
  9. // USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
  10. // NOT CONTROL.
  11.  
  12. // This file creates a global JSON object containing two methods: stringify
  13. // and parse. This file is provides the ES5 JSON capability to ES3 systems.
  14. // If a project might run on IE8 or earlier, then this file should be included.
  15. // This file does nothing on ES5 systems.
  16.  
  17. // JSON.stringify(value, replacer, space)
  18. // value any JavaScript value, usually an object or array.
  19. // replacer an optional parameter that determines how object
  20. // values are stringified for objects. It can be a
  21. // function or an array of strings.
  22. // space an optional parameter that specifies the indentation
  23. // of nested structures. If it is omitted, the text will
  24. // be packed without extra whitespace. If it is a number,
  25. // it will specify the number of spaces to indent at each
  26. // level. If it is a string (such as "\t" or "&nbsp;"),
  27. // it contains the characters used to indent at each level.
  28. // This method produces a JSON text from a JavaScript value.
  29. // When an object value is found, if the object contains a toJSON
  30. // method, its toJSON method will be called and the result will be
  31. // stringified. A toJSON method does not serialize: it returns the
  32. // value represented by the name/value pair that should be serialized,
  33. // or undefined if nothing should be serialized. The toJSON method
  34. // will be passed the key associated with the value, and this will be
  35. // bound to the value.
  36.  
  37. // For example, this would serialize Dates as ISO strings.
  38.  
  39. // Date.prototype.toJSON = function (key) {
  40. // function f(n) {
  41. // // Format integers to have at least two digits.
  42. // return (n < 10)
  43. // ? "0" + n
  44. // : n;
  45. // }
  46. // return this.getUTCFullYear() + "-" +
  47. // f(this.getUTCMonth() + 1) + "-" +
  48. // f(this.getUTCDate()) + "T" +
  49. // f(this.getUTCHours()) + ":" +
  50. // f(this.getUTCMinutes()) + ":" +
  51. // f(this.getUTCSeconds()) + "Z";
  52. // };
  53.  
  54. // You can provide an optional replacer method. It will be passed the
  55. // key and value of each member, with this bound to the containing
  56. // object. The value that is returned from your method will be
  57. // serialized. If your method returns undefined, then the member will
  58. // be excluded from the serialization.
  59.  
  60. // If the replacer parameter is an array of strings, then it will be
  61. // used to select the members to be serialized. It filters the results
  62. // such that only members with keys listed in the replacer array are
  63. // stringified.
  64.  
  65. // Values that do not have JSON representations, such as undefined or
  66. // functions, will not be serialized. Such values in objects will be
  67. // dropped; in arrays they will be replaced with null. You can use
  68. // a replacer function to replace those with JSON values.
  69.  
  70. // JSON.stringify(undefined) returns undefined.
  71.  
  72. // The optional space parameter produces a stringification of the
  73. // value that is filled with line breaks and indentation to make it
  74. // easier to read.
  75.  
  76. // If the space parameter is a non-empty string, then that string will
  77. // be used for indentation. If the space parameter is a number, then
  78. // the indentation will be that many spaces.
  79.  
  80. // Example:
  81.  
  82. // text = JSON.stringify(["e", {pluribus: "unum"}]);
  83. // // text is '["e",{"pluribus":"unum"}]'
  84.  
  85. // text = JSON.stringify(["e", {pluribus: "unum"}], null, "\t");
  86. // // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
  87.  
  88. // text = JSON.stringify([new Date()], function (key, value) {
  89. // return this[key] instanceof Date
  90. // ? "Date(" + this[key] + ")"
  91. // : value;
  92. // });
  93. // // text is '["Date(---current time---)"]'
  94.  
  95. // JSON.parse(text, reviver)
  96. // This method parses a JSON text to produce an object or array.
  97. // It can throw a SyntaxError exception.
  98.  
  99. // The optional reviver parameter is a function that can filter and
  100. // transform the results. It receives each of the keys and values,
  101. // and its return value is used instead of the original value.
  102. // If it returns what it received, then the structure is not modified.
  103. // If it returns undefined then the member is deleted.
  104.  
  105. // Example:
  106.  
  107. // // Parse the text. Values that look like ISO date strings will
  108. // // be converted to Date objects.
  109.  
  110. // myData = JSON.parse(text, function (key, value) {
  111. // var a;
  112. // if (typeof value === "string") {
  113. // a =
  114. // /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
  115. // if (a) {
  116. // return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
  117. // +a[5], +a[6]));
  118. // }
  119. // }
  120. // return value;
  121. // });
  122.  
  123. // myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
  124. // var d;
  125. // if (typeof value === "string" &&
  126. // value.slice(0, 5) === "Date(" &&
  127. // value.slice(-1) === ")") {
  128. // d = new Date(value.slice(5, -1));
  129. // if (d) {
  130. // return d;
  131. // }
  132. // }
  133. // return value;
  134. // });
  135.  
  136. // This is a reference implementation. You are free to copy, modify, or
  137. // redistribute.
  138.  
  139. /*jslint
  140. eval, for, this
  141. */
  142.  
  143. /*property
  144. JSON, apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
  145. getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
  146. lastIndex, length, parse, prototype, push, replace, slice, stringify,
  147. test, toJSON, toString, valueOf
  148. */
  149.  
  150. // Create a JSON object only if one does not already exist. We create the
  151. // methods in a closure to avoid creating global variables.
  152.  
  153. if (typeof JSON !== "object") {
  154. JSON = {};
  155. }
  156.  
  157. (function () {
  158. "use strict";
  159.  
  160. var rx_one = /^[\],:{}\s]*$/;
  161. var rx_two = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
  162. var rx_three = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
  163. var rx_four = /(?:^|:|,)(?:\s*\[)+/g;
  164. var rx_escapable = /[\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
  165. var rx_dangerous = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
  166.  
  167. function f(n) {
  168. // Format integers to have at least two digits.
  169. return n < 10
  170. ? "0" + n
  171. : n;
  172. }
  173.  
  174. function this_value() {
  175. return this.valueOf();
  176. }
  177.  
  178. if (typeof Date.prototype.toJSON !== "function") {
  179.  
  180. Date.prototype.toJSON = function () {
  181.  
  182. return isFinite(this.valueOf())
  183. ? this.getUTCFullYear() + "-" +
  184. f(this.getUTCMonth() + 1) + "-" +
  185. f(this.getUTCDate()) + "T" +
  186. f(this.getUTCHours()) + ":" +
  187. f(this.getUTCMinutes()) + ":" +
  188. f(this.getUTCSeconds()) + "Z"
  189. : null;
  190. };
  191.  
  192. Boolean.prototype.toJSON = this_value;
  193. Number.prototype.toJSON = this_value;
  194. String.prototype.toJSON = this_value;
  195. }
  196.  
  197. var gap;
  198. var indent;
  199. var meta;
  200. var rep;
  201.  
  202. function quote(string) {
  203.  
  204. // If the string contains no control characters, no quote characters, and no
  205. // backslash characters, then we can safely slap some quotes around it.
  206. // Otherwise we must also replace the offending characters with safe escape
  207. // sequences.
  208.  
  209. rx_escapable.lastIndex = 0;
  210. return rx_escapable.test(string)
  211. ? "\"" + string.replace(rx_escapable, function (a) {
  212. var c = meta[a];
  213. return typeof c === "string"
  214. ? c
  215. : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4);
  216. }) + "\""
  217. : "\"" + string + "\"";
  218. }
  219.  
  220. function str(key, holder) {
  221.  
  222. // Produce a string from holder[key].
  223.  
  224. var i; // The loop counter.
  225. var k; // The member key.
  226. var v; // The member value.
  227. var length;
  228. var mind = gap;
  229. var partial;
  230. var value = holder[key];
  231.  
  232. // If the value has a toJSON method, call it to obtain a replacement value.
  233.  
  234. if (value && typeof value === "object" &&
  235. typeof value.toJSON === "function") {
  236. value = value.toJSON(key);
  237. }
  238.  
  239. // If we were called with a replacer function, then call the replacer to
  240. // obtain a replacement value.
  241.  
  242. if (typeof rep === "function") {
  243. value = rep.call(holder, key, value);
  244. }
  245.  
  246. // What happens next depends on the value's type.
  247.  
  248. switch (typeof value) {
  249. case "string":
  250. return quote(value);
  251.  
  252. case "number":
  253.  
  254. // JSON numbers must be finite. Encode non-finite numbers as null.
  255.  
  256. return isFinite(value)
  257. ? String(value)
  258. : "null";
  259.  
  260. case "boolean":
  261. case "null":
  262.  
  263. // If the value is a boolean or null, convert it to a string. Note:
  264. // typeof null does not produce "null". The case is included here in
  265. // the remote chance that this gets fixed someday.
  266.  
  267. return String(value);
  268.  
  269. // If the type is "object", we might be dealing with an object or an array or
  270. // null.
  271.  
  272. case "object":
  273.  
  274. // Due to a specification blunder in ECMAScript, typeof null is "object",
  275. // so watch out for that case.
  276.  
  277. if (!value) {
  278. return "null";
  279. }
  280.  
  281. // Make an array to hold the partial results of stringifying this object value.
  282.  
  283. gap += indent;
  284. partial = [];
  285.  
  286. // Is the value an array?
  287.  
  288. if (Object.prototype.toString.apply(value) === "[object Array]") {
  289.  
  290. // The value is an array. Stringify every element. Use null as a placeholder
  291. // for non-JSON values.
  292.  
  293. length = value.length;
  294. for (i = 0; i < length; i += 1) {
  295. partial[i] = str(i, value) || "null";
  296. }
  297.  
  298. // Join all of the elements together, separated with commas, and wrap them in
  299. // brackets.
  300.  
  301. v = partial.length === 0
  302. ? "[]"
  303. : gap
  304. ? "[\n" + gap + partial.join(",\n" + gap) + "\n" + mind + "]"
  305. : "[" + partial.join(",") + "]";
  306. gap = mind;
  307. return v;
  308. }
  309.  
  310. // If the replacer is an array, use it to select the members to be stringified.
  311.  
  312. if (rep && typeof rep === "object") {
  313. length = rep.length;
  314. for (i = 0; i < length; i += 1) {
  315. if (typeof rep[i] === "string") {
  316. k = rep[i];
  317. v = str(k, value);
  318. if (v) {
  319. partial.push(quote(k) + (
  320. gap
  321. ? ": "
  322. : ":"
  323. ) + v);
  324. }
  325. }
  326. }
  327. } else {
  328.  
  329. // Otherwise, iterate through all of the keys in the object.
  330.  
  331. for (k in value) {
  332. if (Object.prototype.hasOwnProperty.call(value, k)) {
  333. v = str(k, value);
  334. if (v) {
  335. partial.push(quote(k) + (
  336. gap
  337. ? ": "
  338. : ":"
  339. ) + v);
  340. }
  341. }
  342. }
  343. }
  344.  
  345. // Join all of the member texts together, separated with commas,
  346. // and wrap them in braces.
  347.  
  348. v = partial.length === 0
  349. ? "{}"
  350. : gap
  351. ? "{\n" + gap + partial.join(",\n" + gap) + "\n" + mind + "}"
  352. : "{" + partial.join(",") + "}";
  353. gap = mind;
  354. return v;
  355. }
  356. }
  357.  
  358. // If the JSON object does not yet have a stringify method, give it one.
  359.  
  360. if (typeof JSON.stringify !== "function") {
  361. meta = { // table of character substitutions
  362. "\b": "\\b",
  363. "\t": "\\t",
  364. "\n": "\\n",
  365. "\f": "\\f",
  366. "\r": "\\r",
  367. "\"": "\\\"",
  368. "\\": "\\\\"
  369. };
  370. JSON.stringify = function (value, replacer, space) {
  371.  
  372. // The stringify method takes a value and an optional replacer, and an optional
  373. // space parameter, and returns a JSON text. The replacer can be a function
  374. // that can replace values, or an array of strings that will select the keys.
  375. // A default replacer method can be provided. Use of the space parameter can
  376. // produce text that is more easily readable.
  377.  
  378. var i;
  379. gap = "";
  380. indent = "";
  381.  
  382. // If the space parameter is a number, make an indent string containing that
  383. // many spaces.
  384.  
  385. if (typeof space === "number") {
  386. for (i = 0; i < space; i += 1) {
  387. indent += " ";
  388. }
  389.  
  390. // If the space parameter is a string, it will be used as the indent string.
  391.  
  392. } else if (typeof space === "string") {
  393. indent = space;
  394. }
  395.  
  396. // If there is a replacer, it must be a function or an array.
  397. // Otherwise, throw an error.
  398.  
  399. rep = replacer;
  400. if (replacer && typeof replacer !== "function" &&
  401. (typeof replacer !== "object" ||
  402. typeof replacer.length !== "number")) {
  403. throw new Error("JSON.stringify");
  404. }
  405.  
  406. // Make a fake root object containing our value under the key of "".
  407. // Return the result of stringifying the value.
  408.  
  409. return str("", {"": value});
  410. };
  411. }
  412.  
  413. // If the JSON object does not yet have a parse method, give it one.
  414.  
  415. if (typeof JSON.parse !== "function") {
  416. JSON.parse = function (text, reviver) {
  417.  
  418. // The parse method takes a text and an optional reviver function, and returns
  419. // a JavaScript value if the text is a valid JSON text.
  420.  
  421. var j;
  422.  
  423. function walk(holder, key) {
  424.  
  425. // The walk method is used to recursively walk the resulting structure so
  426. // that modifications can be made.
  427.  
  428. var k;
  429. var v;
  430. var value = holder[key];
  431. if (value && typeof value === "object") {
  432. for (k in value) {
  433. if (Object.prototype.hasOwnProperty.call(value, k)) {
  434. v = walk(value, k);
  435. if (v !== undefined) {
  436. value[k] = v;
  437. } else {
  438. delete value[k];
  439. }
  440. }
  441. }
  442. }
  443. return reviver.call(holder, key, value);
  444. }
  445.  
  446. // Parsing happens in four stages. In the first stage, we replace certain
  447. // Unicode characters with escape sequences. JavaScript handles many characters
  448. // incorrectly, either silently deleting them, or treating them as line endings.
  449.  
  450. text = String(text);
  451. rx_dangerous.lastIndex = 0;
  452. if (rx_dangerous.test(text)) {
  453. text = text.replace(rx_dangerous, function (a) {
  454. return "\\u" +
  455. ("0000" + a.charCodeAt(0).toString(16)).slice(-4);
  456. });
  457. }
  458.  
  459. // In the second stage, we run the text against regular expressions that look
  460. // for non-JSON patterns. We are especially concerned with "()" and "new"
  461. // because they can cause invocation, and "=" because it can cause mutation.
  462. // But just to be safe, we want to reject all unexpected forms.
  463.  
  464. // We split the second stage into 4 regexp operations in order to work around
  465. // crippling inefficiencies in IE's and Safari's regexp engines. First we
  466. // replace the JSON backslash pairs with "@" (a non-JSON character). Second, we
  467. // replace all simple value tokens with "]" characters. Third, we delete all
  468. // open brackets that follow a colon or comma or that begin the text. Finally,
  469. // we look to see that the remaining characters are only whitespace or "]" or
  470. // "," or ":" or "{" or "}". If that is so, then the text is safe for eval.
  471.  
  472. if (
  473. rx_one.test(
  474. text
  475. .replace(rx_two, "@")
  476. .replace(rx_three, "]")
  477. .replace(rx_four, "")
  478. )
  479. ) {
  480.  
  481. // In the third stage we use the eval function to compile the text into a
  482. // JavaScript structure. The "{" operator is subject to a syntactic ambiguity
  483. // in JavaScript: it can begin a block or an object literal. We wrap the text
  484. // in parens to eliminate the ambiguity.
  485.  
  486. j = eval("(" + text + ")");
  487.  
  488. // In the optional fourth stage, we recursively walk the new structure, passing
  489. // each name/value pair to a reviver function for possible transformation.
  490.  
  491. return (typeof reviver === "function")
  492. ? walk({"": j}, "")
  493. : j;
  494. }
  495.  
  496. // If the text is not JSON parseable, then a SyntaxError is thrown.
  497.  
  498. throw new SyntaxError("JSON.parse");
  499. };
  500. }
  501. }());

14、javascript 变量加var 和 不加var区别 

一、外部的为全局,内部的为局部变量;

二、加var为局部变量(在方法内),不加var为全局变量(当方法内有一次使用后)。

在写jquery plugin的时候,不小心没加var 声明变量(比如option),导致成为全局变量,多个容器同时初始化组件的时候,

所有容器的option都变成了最后渲染的容器的option,于是各种蛋疼诡异的事情就发生了。

15、datagrid数据和json定制数据合并

场景:easyui-datagrid组件获取到原始数据,根据datagrid中的几个field属性的值作为定位某行的索引,根据这个索引去json定制数据中取值合并。

核心算法:

  1. function combineDataGrid(dataJson,paramJson,indexKeys){// indexKeys 索引fields,数组:['field1','field2'...]
  2. var rows = dataJson.rows;
  3. $.each(rows,function(index,item){
  4. var keyIndex = '';
  5. $.each(indexKeys,function(index,value){
  6. if(index == 0) keyIndex += item[value];
  7. else keyIndex += ','+item[value];
  8. });
  9. if(paramJson[keyIndex] && typeof paramJson[keyIndex] =="object")
  10. item = $.extend(item,paramJson[keyIndex]);
  11. });
  12. return dataJson;
  13. }

demo【jsp】:

  1. <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta charset="UTF-8">
  6. <meta charset="utf-8">
  7. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  8.  
  9. <!-- Bootstrap core CSS -->
  10. <link href="<%=request.getContextPath() %>/js/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  11.  
  12. </head>
  13. <body>
  14. <div class="contener">
  15. <div class="row">
  16. <div class="col-sm-6">
  17. <div class="panel panel-default">
  18. <div class="panel-heading">
  19. dataGrid 数据
  20. </div>
  21. <div class="panel-body">
  22. var dataJson = {"total":28,"rows":[ <br>
  23. {"productid":"FI-SW-01","productname":"Koi"},<br>
  24. {"productid":"K9-DL-01","productname":"Dalmation"},<br>
  25. {"productid":"RP-SN-01","productname":"Rattlesnake"},<br>
  26. {"productid":"RP-SN-01","productname":"Rattlesnake"},<br>
  27. {"productid":"RP-LI-02","productname":"Iguana"}<br>
  28. ]}
  29. </div>
  30. </div>
  31. </div>
  32.  
  33. <div class="col-sm-6">
  34. <div class="panel panel-default">
  35. <div class="panel-heading">
  36. 要合并的属性
  37. </div>
  38. <div class="panel-body">
  39. var paramJson = {<br>
  40. 'FI-SW-01,Koi':{name:'tomy',address:'北京海淀'},<br>
  41. 'RP-SN-01,Rattlesnake':{age: 21},<br>
  42. 'RP-LI-02,Iguana':{sex:'男'}<br>
  43. };
  44. </div>
  45. </div>
  46. </div>
  47. </div>
  48.  
  49. <div class="row">
  50. <div class="col-sm-12">
  51. <div class="panel panel-default">
  52. <div class="panel-heading">
  53. 合并后结果
  54. </div>
  55. <div class="panel-body">
  56. <p id="result"></p>
  57. </div>
  58. </div>
  59. </div>
  60. </div>
  61. </div>
  62.  
  63. </body>
  64. <script src="<%=request.getContextPath()%>/js/jquery/jquery-1.8.3.js"></script>
  65. <script src="<%=request.getContextPath() %>/js/bootstrap/js/bootstrap.min.js"></script>
  66. <script type="text/javascript">
  67. var dataJson = {"total":28,"rows":[
  68. {"productid":"FI-SW-01","productname":"Koi"},
  69. {"productid":"K9-DL-01","productname":"Dalmation"},
  70. {"productid":"RP-SN-01","productname":"Rattlesnake"},
  71. {"productid":"RP-SN-01","productname":"Rattlesn"},
  72. {"productid":"RP-LI-02","productname":"Iguana"}
  73. ]};
  74. var paramJson = {'FI-SW-01,Koi':{productname:'tomy',address:'北京海淀'},
  75. 'RP-SN-01,Rattlesnake':{age: 21},
  76. 'RP-LI-02,Iguana':{sex:'男'}};
  77. var indexKeys = ['productid','productname'];
  78. function combineDataGrid(dataJson,paramJson,indexKeys){
  79. var rows = dataJson.rows;
  80. $.each(rows,function(index,item){
  81. var keyIndex = '';
  82. $.each(indexKeys,function(index,value){
  83. if(index == 0) keyIndex += item[value];
  84. else keyIndex += ','+item[value];
  85. });
  86. if(paramJson[keyIndex] && typeof paramJson[keyIndex] =="object")
  87. item = $.extend(item,paramJson[keyIndex]);
  88. });
  89. return dataJson;
  90. }
  91. combineDataGrid(dataJson,paramJson,indexKeys);
  92.  
  93. $("#result").append('var dataJson = {"total":28,"rows":[');
  94. $.each(dataJson.rows,function(index,item){
  95. $("#result").append('<br>' +JSON.stringify(item));
  96. });
  97. $("#result").append('<br>]}');
  98.  
  99. </script>
  100. </html>

效果:

16、页面多级嵌套iframe超时登出,整体登出处理

不正常情况:(正确应该是整个首页都应该跳到登陆界面)

处理方法:(在登陆页面加入如下脚本)

  1. <script type="text/JavaScript">
  2. var b = window.top!=window.self; // 是否和顶级窗口同级
  3. if(b) window.top.logoutSys(); // 调用顶级窗口的登出方法
  4. </script>

17、js实现文件下载

  1. // url方式
    function downloadFile(url) {
  2. try{
  3. var elemIF = document.createElement("iframe");
  4. elemIF.src = url;
  5. elemIF.style.display = "none";
  6. document.body.appendChild(elemIF);
  7. }catch(e){
  8.  
  9. }
  10. }
  1. // 表单提交返回数据方式
    function downloadFile(url, paramsInput) {
  2. var formStr = null,hideIfm=null;
  3. $("body").find("form[target='hideIframe']").remove();
  4. $("body").find("iframe[name='hideIframe']").remove();
  5. formStr = $('<form style="visibility:hidden;" target="hideIframe" method="POST" action="' + url + '">'
            + '<input type="hidden" name="op" value="' + paramsInput.op + '" />'
            + '<input type="hidden" name="name" value="' + paramsInput.name + '" />'
  6. + '<input type="hidden" name="params" value="' + paramsInput.params + '" />'
           + '</form>');
  7. hideIfm = $("<iframe name='hideIframe'></iframe>").hide();
  8. $("body").append(hideIfm);
  9. $("body").append(formStr);
  10. formStr.get(0).submit();
  11. }

18、js监测系统信息(32位、64位)及监测浏览器版本

  1. function getCPU(){
  2. var agent=navigator.userAgent.toLowerCase();
  3. if(agent.indexOf("win64")>=0||agent.indexOf("wow64")>=0) return "x64";
  4. return navigator.cpuClass;
    }
  1. <script type="text/javascript">
  2. var userAgent = navigator.userAgent,
  3. rMsie = /(msie\s|trident.*rv:)([\w.]+)/,
  4. rFirefox = /(firefox)\/([\w.]+)/,
  5. rOpera = /(opera).+version\/([\w.]+)/,
  6. rChrome = /(chrome)\/([\w.]+)/,
  7. rSafari = /version\/([\w.]+).*(safari)/;
  8. var browser;
  9. var version;
  10. var ua = userAgent.toLowerCase();
  11. function uaMatch(ua){
  12. var match = rMsie.exec(ua);
  13. if(match != null){
  14. return { browser : "IE", version : match[2] || "0" };
  15. }
  16. var match = rFirefox.exec(ua);
  17. if (match != null) {
  18. return { browser : match[1] || "", version : match[2] || "0" };
  19. }
  20. var match = rOpera.exec(ua);
  21. if (match != null) {
  22. return { browser : match[1] || "", version : match[2] || "0" };
  23. }
  24. var match = rChrome.exec(ua);
  25. if (match != null) {
  26. return { browser : match[1] || "", version : match[2] || "0" };
  27. }
  28. var match = rSafari.exec(ua);
  29. if (match != null) {
  30. return { browser : match[2] || "", version : match[1] || "0" };
  31. }
  32. if (match != null) {
  33. return { browser : "", version : "0" };
  34. }
  35. }
  36. var browserMatch = uaMatch(userAgent.toLowerCase());
  37. if (browserMatch.browser){
  38. browser = browserMatch.browser;
  39. version = browserMatch.version;
  40. }
  41. document.write(browser+version);
  42. </script>

19、jquery html方法失效问题(ie8 及以下)

今天遇到jquery中的html方法使用不了,只能用完最基本的innerHTML把内容展示出来。具体原因还没找到,肯定跟内容有关

  1. $("#content").html(data.content); // ie8及以下情况下异常
  2. $("#content")[0].innerHTML = data.content;

下面是其它网友的补充:

jQuery一般来说还是很好用的,但有时候它也会有些问题的,比如jQuery的html()方法设置html代码,在一种情况下,ie6、ie7、ie8 下是不能设置html代码的。本文说的问题只针对ie8(包括ie8)以下的浏览器。

  1.什么情况下IE6、IE7、IE8 jQuery.html("xxx")方法会设置不上html代码?

  答:当被加载的的html代码里面出现以下情况,ie8(包括ie8)以下是设置不上html代码的:

    a) 被设置的html代码中包含引用其他js的,如:<script src="Stone.js" type="text/javascript"></script> 这种情况下,设置html代码无效。
    b) 被设置的html代码中包含js 方法的,如:function Stone(){ alert("我叫MT"); },设置html代码无效。
    c) 被设置的html代码中有css 样式的,如:.Stone ul li{ list-style:none;float:left; }等,设置的html代码无效。[附加:被设置的html代码中如果包含引用其他外部

      样式的,比如:<link href="../Css/style.css" rel="stylesheet" type="text/css" />,虽然不会影响html设置,但是被引用的css是无效的,是没有样式的。]

  2.原因分析:

  答:被设置的html,jQuery只是单纯的解析为html,不会去理会其他的因素和代码,所有导致上述问题的出现。

  3.解决方案:

  答:去掉被设置的js引用css引用和代码即可解决。

20、Ajax中window.location.href无法跳转的解决办法

  1. $.ajax({
  2. //async:false, //设置ajax的同步
  3. type: "get", //get方式
  4. url: "../handler/QueryQuestionnaire.ashx",
  5.  
  6. //返回数据成功,将返回的json数据解析,显示在课程信息列表中
  7. success: function (strJson) {
  8.  
  9. //检查后台返回的数据
  10. var dataArray = eval(strJson);
  11.  
  12. window.location.href = url;//要访问的网址
  13. },
  14. //返回数据失败,弹出错误显示
  15. error: function (XmlHttpRequest, textStatus, errorThrown) {
  16. alert(XmlHttpRequest.responseText);
  17. }
  18. });
    return false;  

一般情况下要加上:return false

21、事件绑定匿名函数变量传参问题

  1. function uploadFile(ob,cnt) {
  2. var url = getUrl(ob);
  3. if(ob.files){
  4. for(var i=0;i<ob.files.length;i++){
  5. var uidRan = Math.round(Math.random()*10000000000);//改成const uiRan申明方式(常量)var fd = new FormData();
  6. fd.append("fileInput", ob.files[i]);
  7. var xhr = new XMLHttpRequest();
  8. xhr.upload.addEventListener("progress", function(){
  9. console.info("传入的值:"+uidRan);
  10. //uploadProgress(event,cnt,{uid:uidRan});
  11. }, false);
  12. console.info(uidRan);
  13. xhr.addEventListener("load", uploadComplete, false);
  14. xhr.addEventListener("error", function(){uploadFailed(event,cnt);}, false);
  15. xhr.addEventListener("abort", uploadCanceled, false);
  16. xhr.open("POST", url);//修改为自己服务器接口地址
  17. xhr.send(fd);
  18. }
  19. }
  20. }

改成const uidRan = Math.round(Math.random()*10000000000);申明后正常

22、复制文本到剪切板

核心js:(亲测ie google兼容,其他没有测试)

  1. function copyText(text){
  2. var textCtner = document.createElement("div");
  3. textCtner.innerHTML = text;
  4. var txt = textCtner.innerText;//之所以中间转换,防止text中有dom格式的文本,会导致textarea.innerHTML设置失效
  5.  
  6. var textarea = document.createElement("textarea");
  7. textarea.innerHTML = txt;
  8. document.body.appendChild(textarea);
  9. textarea.select(); // 选择对象
  10. document.execCommand("Copy"); // 执行浏览器复制命令
  11. document.body.removeChild(textarea);
  12. }

23、radio之trgger触发事件问题

dom容器:

  1. <div class="inputRadio" data-option="{changeInput:'changeEvt()'}"></div>
  2. <button onclick="clickEvt()">trgger</button>

脚本:

  1. <script type="text/javascript">
  2. function changeEvt(){
  3. alert(1);
  4. }
  5. function clickEvt(){
  6. $("input[name='age'][value='0']").attr("checked",true);
  7. $("input[name='age'][value='0']").trigger("click");
  8. }
  9. (function ($) {
  10. $.fn.inputRadio = function (op) {
  11. return this.each(function(){
  12. var changeInput = eval("(" + $(this).attr("data-option") + ")").changeInput;
  13. var id = $(this).attr("id");
  14. var txt = $(this),
  15. strHtml = '<input type="radio" name="age" value="1" "/>是'+
  16. '<input type="radio" name="age" value="0" "/>否';
  17. txt.after(strHtml);
  18. txt.remove();
  19. $('input[name="age"]').bind("click", function(){
  20. var nameA = $(this).attr("name");
  21. if(changeInput){
  22. eval(changeInput);
  23. }
  24. });
  25. });
  26. };
  27. })(jQuery);
  28.  
  29. $(".inputRadio").inputRadio();
  30. </script>

会发现点击按钮时,先执行changeEvt()方法,然后才选中目标,这样就会造成无法及时获取选中的值。

改进changeEvt():

  1. function clickEvt(){
  2. $("input[name='age'][value='0']").attr("checked",true);
  3. setTimeout(function(){
  4. $("input[name='age'][value='0']").trigger("click");
  5. },0);
  6. }

如此便能及时获取到选中的值

24、js文件中使用EL表达式方案

  如果js非要放入单独文件中,可以把js文件命名为.jsp文件就可以了,这样里面el就能运行,也就是服务器可以执行这个文件了。无非页面引用的时候引用jsp就可以了。
<script src="myjs.jsp" type="text/javascript> </script>

25、计算容器剩余高度

  在开发table组件时,实现表格高度依据父容器动态计算,需要将可见元素的高度都减除掉,代码逻辑如下:

  1. <script>
  2. const SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
  3. const MOZ_HACK_REGEXP = /^moz([A-Z])/;function _usableHeight(node){
  4. let parentNode = node.parentNode,
  5. firstNode = parentNode.firstElementChild,
  6. lastNode = parentNode.lastElementChild,
  7. nextNode = node.nextElementSibling,
  8. usableHeight = parentNode.clientHeight;//parseInt(getStyle(parentNode, 'height'));
  9. //let tbHeight = usableHeight*(this.height.replace('%','')-0)/100;
  10. /* reduce height of other visible doms */
  11. let fistMarginTop = parseInt(getStyle(firstNode, 'margin-top'))||0,
  12. fistTop = parseInt(getStyle(firstNode, 'top'))||0;
  13. usableHeight -= node.offsetTop - firstNode.offsetTop + fistMarginTop + fistTop;
  14. if(lastNode != node){
  15. let nextMarginTop = parseInt(getStyle(nextNode, 'margin-top'))||0,
  16. nextTop = parseInt(getStyle(nextNode, 'top'))||0,
  17. lastMarginBottom = parseInt(getStyle(lastNode, 'margin-bottom'))||0,
  18. lastBottom = parseInt(getStyle(lastNode, 'bottom'))||0;
  19. var lastBth = lastNode.offsetTop - nextNode.offsetTop + lastNode.offsetHeight + nextMarginTop + nextTop + lastMarginBottom + lastBottom;
  20. usableHeight -= lastBth;
  21. }
  22. let nodeMarginBottom = parseInt(getStyle(node, 'margin-bottom')) ||0,
  23. nodeBottom = parseInt(getStyle(node, 'margin-bottom'))||0;
  24. usableHeight -= node.offsetHeight + nodeMarginBottom + nodeBottom;//parseInt(getStyle(node, 'height'));return usableHeight;
  25. }
  26. function camelCase(name) {
  27. return name.replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter,
  28. offset) {
  29. return offset ? letter.toUpperCase() : letter;
  30. }).replace(MOZ_HACK_REGEXP, 'Moz$1');
  31. }
  32. function getStyle(element, styleName) {
  33. if (!element || !styleName) return null;
  34. styleName = camelCase(styleName);
  35. if (styleName === 'float') {
  36. styleName = 'cssFloat';
  37. }
  38. try {
  39. const computed = document.defaultView.getComputedStyle(element, '');
  40. return element.style[styleName] || computed ? computed[styleName] : null;
  41. } catch (e) {
  42. return element.style[styleName];
  43. }
  44. }
  45. </script>

注意: nextSibling、lastChild,IE将跳过在节点之间产生的空格文档节点(如:换行字符),而Mozilla不会这样——FF会把诸如空格换行之类的排版元素视作节点读取,因此,在ie 中用nextSibling便可读取到的下一个节点元素,在FF中就需要这样写:nextElementSibling了。

26、禁用浏览器回退 

  1. // 禁止浏览器回退
    history.pushState(null, null, document.URL);
  2. window.addEventListener('popstate', function () {
  3. history.pushState(null, null, document.URL);
  4. });

js高级应用的更多相关文章

  1. JS高级前端开发群加群说明及如何晋级

    JS高级前端开发群加群说明 一.文章背景: 二. 高级群: 三. 加入方式: 四. 说明:   一.文章背景: 去年年初建了几个群,在不经意间火了,一直排在“前端开发”关键字搜索结果第一名.当然取得这 ...

  2. 前端进阶试题css(来自js高级前端开发---豪情)既然被发现了HOHO,那我就置顶了嘿嘿!觉得自己技术OK的可以把这套题目做完哦,然后加入高级前端的社区咯

    http://www.cnblogs.com/jikey/p/4426105.html js高级前端开发加群方法(此群很难进,里面纯技术,严禁广告,水群) 完整题目做完发邮箱(jikeytang@16 ...

  3. Node.js高级编程读书笔记Outline

    Motivation 世俗一把,看看前端的JavaScript究竟能做什么. 顺便检验一下自己的学习能力. Audience 想看偏后台的Java程序员关于前端JavaScript的认识的职业前端工程 ...

  4. 读JS高级——第五章-引用类型 _记录

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  5. js高级程序设计笔记之-addEventListener()与removeEventListener(),事件解除与绑定

    js高级程序设计笔记之-addEventListener()与removeEventListener(),事件解除与绑定 addEventListener()与removeEventListener( ...

  6. 《JS高级程序设计》笔记 —— 解析查询字符串

    今天在继续翻阅<JS高级程序设计>的时候,正好翻到location对象这一小节,其中有一部分就是讲的解析查询字符串.看到这个内容立马想到了做去哪儿秋招笔试题的时候有这么一道题. 去哪儿笔试 ...

  7. js 高级函数 之示例

    js 高级函数作用域安全构造函数 function Person(name, age)    {        this.name = name;        this.age = age;     ...

  8. 惰性函数——JS高级

    我们先来看一下js的异步提交. XHR我们在原生的时候常常用到,因为常用到,我们更多把封装到了工具库中 先看下他最常用的实现 // 旧方法 function createXHR() { var xhr ...

  9. 《Node.js 高级编程》简介与第二章笔记

    <Node.js 高级编程> 作者简介 Pedro Teixerra 高产,开源项目程序员 Node 社区活跃成员,Node公司的创始人之一. 10岁开始编程,Visual Basic.C ...

  10. js高级-面向对象继承

    一.工厂模式创建对象及优缺点 继承就是把公共的部分抽象出来作为父类,基类.吃饭,跑步等 var a = {}; //批量创建不方便,不能重复设置公共属性的代码 //工厂模式出现了,创建10个Cat对象 ...

随机推荐

  1. Eclipse编程时的快捷键总结

    " alt + / " 快捷键是代码补全功能 输入" syso alt + / "会自动补全成System.out.println();

  2. PowerDesginer 生成的Oracle 11g 组合触发器代码编译错误(29): PLS-00103

    问题描述: 采用PowerDesigner15针对Oracle 11g 创建物理数据模型,想实现一个字段的自增,采用如下步骤: 1.创建序列,命名为Sequence_1; 2.在自增字段编辑窗口中,选 ...

  3. AWT事件处理

    AWT事件处理基本概念 AWT事件处理过程中,主要涉及3类对象: ①   Event(事件):用户对组件的一个操作,称之为一个事件,以类的形式出现,例如,键盘操作对应的事件类是KeyEvent.其实例 ...

  4. iOS 上架被拒原因保存

    一.后台一直在获取用户的定位,需要给用户电池消耗提示 Your app uses the Location Background mode but does not include the requi ...

  5. iOS开发:开发证书知识点总结

    1. Error: An App ID with identifier "*" is not avaliable. Please enter a different string. ...

  6. (转)myeclipse插件—SVN分支与合并详解【图】

    svn作为版本控制软件被广泛用于众多公司的开发团队中,最多的场景就是一个项目上传svn后,一个组内的小伙伴在上边提交和更新代码以及解决冲突,其实这只是发挥了svn的很小的一部分功能. 先稍微介绍一下s ...

  7. miniui中常用的状态显示方式

    1.查询sys_code表得到对应的状态 考生状态:<input class="mini-combobox" style="" textField=&qu ...

  8. 定义/修改列时 NULL

    mysql的文档说明: column_definition:     col_name type [NOT NULL | NULL] [DEFAULT default_value]         [ ...

  9. Nginx Location配置总结

    Nginx Location配置总结 语法规则: location [=|~|~*|^~] /uri/ { - }= 开头表示精确匹配^~ 开头表示uri以某个常规字符串开头,理解为匹配 url路径即 ...

  10. 创建并追加img元素(jquery!)

    有几种方法 但都需要你指定一个节点 根据这个节点进行添加 如现有一节点Id为pr:一,向该节点内部后方添加:1 $("#pr").append("<img src= ...