zoukankan      html  css  js  c++  java
  • jQuery获取地址栏中的链接参数

    原文链接:http://caibaojian.com/177.html

    问题描述

    今天做一个主题,有一个需求是根据不同的页面来做,虽然php也可以做到,不过考虑到自己的特效代码都是在jQuery上完成,想着能否直接通过获取地址栏中的链接参数里面的数字直接来实现效果。

    假设页面的地址是这样子的。http://caibaojian.com/p/165 ,那么我要获取最后的一个数字165,可以通过这样子的代码·

    var url= window.location.href;
    var index = url.substring(url.lastIndexOf('/') + 1);

    但是这样子有缺陷,假如我获取到的地址不是这样子的形式,而是http://caibaojian.com/tools的话,那么这个index的值就不是一个数字了。

    解决方案

    下面这种可能会更好呢?

    var lastBit = url.substring(url.lastIndexOf('/') + 1).match(/[^/]*$/)[0];
    var lastDigits = url.substring(url.lastIndexOf('/') + 1).match(/[0-9]*$/)[0];  // 获取的是数字部分

    获取查询值

    //code from http://caibaojian.com/177.html
    <script type="text/javascript">
    (function($){
    $.getUrlParam = function(name)
    {
    var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r!=null) return unescape(r[2]); return null;
    }
    })(jQuery);
    $(function(){
    alert(window.location.href);
    alert($.getUrlParam('page'));
    })
    </script>

    http://www.caibaojian.com/front?page=5

    当一个页面的地址是上面这个,那么我们使用了上面的jQuery代码,就会弹出一个数字5了。

    内容扩展

    对于像下面这样的网址

    http://www.caibaojian.com:80/fisker/post/0703/window.location.html?ver=1.0&id=6#imhere

    我们可以用javascript获得其中的各个部分
    1, window.location.href-----------整个URl字符串(在浏览器中就是完整的地址栏)
    本例返回值: http://www.caibaojian.com:80/fisker/post/0703/window.location.html?ver=1.0&id=6#imhere

    2,window.location.protocol---------URL 的协议部分
    本例返回值:http:

    3,window.location.host----------URL 的主机部分
    本例返回值:www.caibaojian.com

    4,window.location.port-----URL 的端口部分
    如果采用默认的80端口(update:即使添加了:80),那么返回值并不是默认的80而是空字符
    本例返回值:""

    5,window.location.pathname(URL 的路径部分(就是文件地址))
    本例返回值:/fisker/post/0703/window.location.html

    6,window.location.search-------查询(参数)部分
    除了给动态语言赋值以外,我们同样可以给静态页面,并使用javascript来获得相信应的参数值
    本例返回值:?ver=1.0&id=6

    7,window.location.hash-------锚点
    本例返回值:#imhere


    来源:前端开发博客

  • 相关阅读:
    jquery toggle(listenerOdd, listenerEven)
    struts quick start
    hdu 1518 Square (dfs)
    hdu 2544 最短路 (最短路径)
    hdu 1754 I Hate It (线段树)
    hdu 1856 More is better (并查集)
    hdu 1358 Period (KMP)
    hdu 2616 Kill the monster (DFS)
    hdu 2579 Dating with girls(2) (bfs)
    zoj 2110 Tempter of the Bone (dfs)
  • 原文地址:https://www.cnblogs.com/jianmingyuan/p/6709008.html
Copyright © 2011-2022 走看看