我发现了这段代码,它非常有用:
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (!results) { return 0; }
return results[1] || 0;}
}
如果 url/查询字符串是 xyz.com/index.html?lang=de
只需调用 var langval = $.urlParam('lang');你已经得到它了
--
我的信息来自点击图像,因此我创建了以下代码:
$('#admin-slideshow img').click(function() {
alert($(this).attr('src'));
}
如果代码是:
<a href="#"><img src="image.php?url=image.jpg&tid=1&opn=1" /></a>
它会发出警报 (image.php?url=image.jpg&tid=1&opn=1)。
我的聪明想法是添加代码片段 $(this).attr('src');并将其替换为 window.location.href。这不起作用。有什么建议吗?
$('#admin-slideshow img').click(function() {
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec($(this).attr('src'));
if (!results) { return 0; }
return results[1] || 0;}
}
}
最佳答案
试试这个,
$.urlParam = function(name, src){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec( src || window.location.href); // if src is undefined defualt is window.location.href
if (!results) { return 0; }
return results[1] || 0;
}
将其用作
$.urlParam('lang',window.location.href); // for url or just $.urlParam('lang');
$.urlParam('lang',$('#admin-slideshow img').attr('src')); // for images
$('#admin-slideshow img').click(function() {
alert($.urlParam('opn',this.src));
}
关于jquery从img src而不是window.location.href获取变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3573211/