知识累计日常_17.11.14

来源:互联网 发布:软件模块间接口 编辑:程序博客网 时间:2024/05/29 09:14


1.substr(start,length): 从字符串第几位开始提取,提取多少位

例子:

<script type="text/javascript">var str="Hello world!"document.write(str.substr(3))</script>
输出结果 lo world!

综合实例:

    function getQueryString(name) {    /定义函数
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)","i");    //定义正则规则
        var r = window.location.search.substr(1).match(reg);    /从url?之后1位开始进行正则匹配
        if (r != null) return decodeURI(r[2]); return null;    //如果不为null 返回一个数组 否则返回null

}

输出结果 url? 号后面name对应的值


2.indexOf():indexOf 方法返回一个整数值,指出 String 对象内子字符串的开始位置。如果没有找到子字符串,则返回-1。

实例:判断页面url的值,并进行拼接。

if(desc){
        if(desc.indexOf("用户不存在") > -1){//如果有用户不存在这几个字
        if(location.search.indexOf("name") < 0 ){//如果不存在name值
            document.getElementById("desc").innerHTML='用户不存在,请登录系统注册.';//页面显示'用户不存在,请登录系统注册.'
            document.getElementById("errorPrompt").style.display="block";// 页面元素css添加displayblock
            }else{
            var name = getQueryString("name");
            var dept = getQueryString("dept");
            var tel = getQueryString("tel");
            document.getElementById("desc").innerHTML='用户不存在,请先<a href="${pageContext.request.contextPath}/reg.htm?name='+ name +' &tel= ' + tel + ' &dept=' +dept+ '" class="reg">注册</a>。';
           
            }
        }else{
        document.getElementById("desc").innerHTML=desc;
       
        }


3.window.history :  

HTML5为history对象添加了两个新方法,history.pushState()和history.replaceState(),用来在浏览历史中添加和修改记录。

history.pushState方法接受三个参数,依次为:

state:一个与指定网址相关的状态对象,popstate事件触发时,该对象会传入回调函数。如果不需要这个对象,此处可以填null。

title:新页面的标题,但是所有浏览器目前都忽略这个值,因此这里可以填null。

url:新的网址,必须与当前页面处在同一个域。浏览器的地址栏将显示这个网址。

假定当前网址是example.com/1.html,我们使用pushState方法在浏览记录(history对象)中添加一个新记录。

var stateObj = { foo: 'bar' };

history.pushState(stateObj, 'page 2', '2.html');

添加上面这个新记录后,浏览器地址栏立刻显示example.com/2.html,但并不会跳转到2.html,甚至也不会检查2.html是否存在,它只是成为浏览历史中的最新记录。假定这时你访问了google.com,然后点击了倒退按钮,页面的url将显示2.html,但是内容还是原来的1.html。你再点击一次倒退按钮,url将显示1.html,内容不变。


实例:

 function addHistoryEntity(){
        if(history.pushState){//如果历史记录为真
            history.pushState('state1',null,'#foo'); //创建一个历史地址 xxxxx#foo
        }else{
        document.getElementById("goFoo").click();
        }
    }
    function detectBack(){
        if(history.pushState){//如果历史记录为真
            window.onpopstate=function(){ //浏览记录出现变化时调用函数                
                logout(); //调用函数logout                
            }
        }
        else{
        $(window).on("hashchange",function(){
                if(location.hash=="#foo"){
                    return; //终止
                }
                logout(); //调用logout()
            });
        }
    }
    function logout(){
    location.href="${pageContext.request.contextPath}/logout"; //页面跳转
    }