本文将通过实际例子讲解怎么使用javascript或者jquery获取地址

优采云 发布时间: 2021-08-15 01:14

  本文将通过实际例子讲解怎么使用javascript或者jquery获取地址

  本文将通过实例讲解如何使用javascript或jquery获取地址url参数。我希望你会喜欢。问题描述 今天要做一个主题,有一个要求是根据不同的页面来做。虽然php也可以,但是考虑到我的特效代码是在jQuery上做的,不知道能不能直接在地址栏中获取地址。链接参数中的数字直接达到效果。假设页面地址是这样的。 ,然后我想得到最后一个数字165,通过这段代码

  var url= window.location.href;

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

  但这是有缺陷的。如果我得到的地址不是这种形式,而是形式,那么这个索引的值就不是数字。以下哪种解决方案可能更好?

  var lastBit = url.substring(url.lastIndexOf('/') + 1).match(/[^/]*$/)[0];

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

  获取查询值 JavaScript 版本:

  function getUrlParam(name){

var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");

var r = window.location.search.substr(1).match(reg);

if (r!=null) return unescape(r[2]); return null;

}

//获取http://caibaojian.com/?p=177.html的p值

getUrlParam('p'); //输出177

  jQuery 版本:

  

(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'));

})

  当一个页面的地址是上面的时候,那么我们使用上面的jQuery代码,会弹出一个数字5。 Content extensionFor URLs如下: 80/fisker/post/0703/window.location.html?ver=1.0&id=6#imhere 我们可以使用javascript来获取各个部分1,window.location.href-- --------整个 URl 字符串(在浏览器中是完整的地址栏) 本例返回值: :80/fisker/post/0703/window.location.html?ver=1. 0&id= 6#imhere2,window.location.protocol---------URL的协议部分。本例返回值:http:3,window.location.host-----of the URL 本例中host部分的返回值:4、window.location.port---- -如果URL的端口部分使用默认的80端口(更新:即使添加:80),返回值也不是默认的80。是空字符。本例返回值:“” 5、window.location.pathname(URL的路径部分(即文件地址)) 本例返回值:/fisker/post/0703/window.location.html6,window.location.search-- -----除了在查询(参数)部分给动态语言赋值,我们还可以为静态页面赋值,使用javascript获取我们认为本例中应该返回的参数值: ?ver=1.0&id= 67, window.location.hash-------本例中的锚返回值:#imhere

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线