zoukankan      html  css  js  c++  java
  • JS技巧

    一 判断移动终端类型

    1. 判断是否是IE浏览系统

     isIE: function() {
       return (/msie/i).test(navigator.userAgent);
    }

    2. 判断是否是Android浏览系统

    isAndroid: function() {
            var isAndroid = false, androidVersion;
    
            if(navigator.userAgent.indexOf("Android") >= 0 ) {
              androidVersion = parseFloat(navigator.userAgent.slice(navigator.userAgent.indexOf("Android")+8));
              if (androidVersion <= 2.4) {
                  isAndroid = true;
              }
            }
    
            return isAndroid;
     }

    3. 判断是否是Windows Phone 7浏览系统

     fontFaceCheck: function() {
            if (/Windows Phone OS 7/.test(navigator.userAgent)) {
              Modernizr.fontface = false;
              $("html").removeClass("fontface").addClass("no-fontface");
            }
    }

    二 URL Params

    /*
     * URL Params - v1.0 - 8/28/2013
     * http://pastebin.com/yvfeK76y
     *
     * Include this in the document <head> for best results. It will create a global 
     * object "urlParams" that stores all querystring parameters in a URL.
     *
     * Uses/examples:
     * if ("foo" in urlParams) { ... }
     * var foo_value = urlParams["foo"];
     *
     */
    var urlParams = {};
    
    (function() {
        var e, a = /+/g, r = /([^&=]+)=?([^&]*)/g, d = function(s) {
            return decodeURIComponent(s.replace(a, " "));
        }, q = window.location.search.substring(1);
        while (e = r.exec(q)) urlParams[d(e[1])] = d(e[2]);
    })();

    三 获得当天时间

    new Date().getTime()

    四 跳转页面

    var address = "***" ;
    window.location.href="${request.contextPath}"+ address ;

    五 重新加载页面

    location.reload();

    六 JSTL超过一定长度显示省略字符 ...

    <c:choose>
            <c:when test="${fn:length(product.description) ge 250 }">
                <p>
                    <span class="modelHighlightsDescription">${fn:substring(product.description, 0, 200)}...</span>
                </p>
            </c:when>
            <c:otherwise>
                <p>
                    <span class="modelHighlightsDescription"> ${product.description }</span>
                </p>
                </c:otherwise>
    </c:choose>

    七 JSTL格式化货币

    1)新建一个price.tag 文件,放在 %/WEB-INF/tags/shared/format 目录下。

    <%@ tag body-content="empty" trimDirectiveWhitespaces="true" %>
    <%@ attribute name="priceData" required="true" type="de.hybris.platform.commercefacades.product.data.PriceData" %>
    <%@ attribute name="displayFreeForZero" required="false" type="java.lang.Boolean" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
    
    <%--
     Tag to render a currency formatted price.
     Includes the currency symbol for the specific currency.
    --%>
    <c:choose>
        <c:when test="${priceData.value > 0}">
            ${priceData.formattedValue}
        </c:when>
        <c:otherwise>
            <c:if test="${displayFreeForZero}">
                <spring:theme code="text.free" text="FREE"/>
            </c:if>
            <c:if test="${not displayFreeForZero}">
                ${priceData.formattedValue}
            </c:if>
        </c:otherwise>
    </c:choose>

    2)新建一个tag文件,cartItems.tag,引入刚才新建的 price.tag文件

    <%@ taglib prefix="format" tagdir="/WEB-INF/tags/shared/format"%>
    
    <format:price priceData="${entry.priceWithoutCoupon}" displayFreeForZero="true" />

    八 JSTL根据条件显示不同的库存量

    <c:if test="${product.stock.stockLevel gt 0}">
            <c:set var="productStockLevel">${product.stock.stockLevel}&nbsp;<spring:theme code="product.variants.in.stock"/></c:set>
    </c:if>
    <c:if test="${product.stock.stockLevelStatus.code eq 'lowStock'}">
            <c:set var="productStockLevel"><spring:theme code="product.variants.only.left" arguments="${product.stock.stockLevel}"/></c:set>
    </c:if>
    <c:if test="${product.stock.stockLevelStatus.code eq 'inStock' and empty product.stock.stockLevel}">
             <c:set var="productStockLevel"><spring:theme code="product.variants.available"/></c:set>
    </c:if>
    <span class="rci-msg"  style="color: #9c3022;font-weight: bold;">${productStockLevel}</span>

    九 JSTL 使用动态变量

    <c:url value="${facetValue.query.url}" var="facetValueQueryUrl"/>
    <input type="radio" onclick="javascript:location.href='${facetValueQueryUrl}&amp;text=${searchPageData.freeTextSearch}';" >

    十 window 加载 javascript代码

    <script type="text/javascript">
    
    
    function downloadJSAtOnload() {
        var loadScript = document.createElement("script");
        loadScript.src="${fn:substring(url, 0, fn:length(url) - fn:length(uri))}${webroot}resources/vendor/requirejs/require.js";
        loadScript.setAttribute("data-main","${fn:substring(url, 0, fn:length(url) - fn:length(uri))}${webroot}resources/singlePage");
        document.body.appendChild(loadScript);
    }
    
    if (window.addEventListener)
        window.addEventListener("load", downloadJSAtOnload, false);
    else if (window.attachEvent)
        window.attachEvent("onload", downloadJSAtOnload);
    else window.onload = downloadJSAtOnload;
    
    
    </script>

     十一  字符串转数组

    // 字符串转数组
    function convertToArray(original) {
        var arr = original.trim().split(/s*,s*/);
        if(arr[arr.length-1] == "") {
                arr.pop();
        }
        return arr;
    }

    十二 计算百分比率

    function calcPercent(n1, n2) {
        var num1 = parseInt(n1);
        var num2 = parseInt(n2);
        if(num1 && num2) {
            return Math.round((num1 / num2) * 100);
        }else {
            return 0;
        }
    }

    十三 字符串比较

        function compare(n1, n2) {
            var t1 = parseInt(n1);
            var t2 = parseInt(n2);
            if(t1 > t2) {
                return 1;
            }else if(t1 == t2) {
                return 0;
            }else {
                return -1;
            }
        }

    十四 生成32位随机数

    Math.uuid(32);

    十五 左标题栏闪烁

     var newMessageRemind={
          _step: 0,
          _title: document.title,
          _timer: null,
          //显示新消息提示
          show:function(){
            var temps = newMessageRemind._title.replace("【   】", "").replace("【新订单】", "");
            newMessageRemind._timer = setTimeout(function() {
              // newMessageRemind.show();
              newMessageRemind._step++;
              if (newMessageRemind._step == 3) { newMessageRemind._step = 1 };
              if (newMessageRemind._step == 1) { document.title = "【   】" + temps };
              if (newMessageRemind._step == 2) { document.title = "【新订单】" + temps };
            }, 100);
            return [newMessageRemind._timer, newMessageRemind._title];
          },
          //取消新消息提示
          clear: function(){
            clearTimeout(newMessageRemind._timer );
            document.title = newMessageRemind._title;
          }
    
        };
    
    
     if(roles.sysRole){
          setInterval(function () {
            if(!!$.cookie('newOrder')){
              newMessageRemind.show();
            }else{
              newMessageRemind.clear();
            }
          }, 500)
        }

    十六 截取字符串 包含中文处理 * 串,长度,hasDot表示是否增加 "..."

     //  alert(newSubString("字符串截取测试1423456是一个收藏精品学习资料的网站",20,true));  
            function newSubString(str, len, hasDot){ 
                var newLength = 0; 
                var newStr = ""; 
                var chineseRegex = /[^x00-xff]/g; 
                var singleChar = ""; 
                var strLength = str.replace(chineseRegex,"**").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; 
                } 
                 
                if(hasDot && strLength > len){ 
                        newStr += "..."; 
                } 
                return newStr; 
            }

    十七 收集对象属性

    function getKeys(object) {
            var keys = [];
            for (var property in object)
              keys.push(property);
            return keys;
        }

    十八 判断对象是否为空

            function isEmptyObject(obj){
                for(var n in obj){return false} 
                    return true; 
            }

    十九 常用时间方法

    function getCurrentTime(){
        return formatData(new Date(),'MM/dd/yyyy hh:mm');
    }
    
    function getPreviousTime( previousHour) {
         var currTimeStamp = Date.parse( getCurrentTime() );
         var calTimestamp = currTimeStamp - previousHour * 3600 * 1000;
         var previousDate = new Date(calTimestamp);
         //return formatData( previousDate,'MM/dd/yyyy hh:mm');
         return formatData( previousDate,'yyyy-MM-dd hh:mm');
    }

    二十 格式化时间

       function formatData(dataStr,fmt)
        {        
            if(dataStr == undefined)
                return '';
            if(fmt != undefined)
                return new Date(dataStr).format(fmt);
            else
                return new Date(dataStr).format("yyyy-MM-dd hh:mm:ss");
        }  

    二十一 遍历数据

    var days = ["a" , "b" , "c" , "d" , "e" , "f"];
    
    for(var idx in days){
        console.log( idx + "--> " + days[idx] );
    }
  • 相关阅读:
    进程的两种开启方法,进程的常用方法,进程的常用属性
    并发编程简介
    周鸿祎:互联网成功十大案例
    sed用法详解
    awk与sed:一个关于多行处理的例子
    igmpproxy源代码学习——igmpProxyInit()
    获取网络接口信息——ioctl()函数与结构体struct ifreq、 struct ifconf
    unix网络编程——ioctl 函数的用法详解
    九大排序算法再总结
    浅谈《剑指offer》原题:不使用条件、循环语句求1+2+……+n
  • 原文地址:https://www.cnblogs.com/wangshuo1/p/4341561.html
Copyright © 2011-2022 走看看