【发布时间】:2015-06-03 18:52:19
【问题描述】:
这是我的 jsFiddle:http://jsfiddle.net/jsFiddlePlayer/vhg7csb7/10/
我正在尝试将StackOverflow question 中的答案作为 jQuery 插件实现,但没有运气。 getParameterByName 函数读取 URL 的查询字符串变量并返回参数中指示的变量。但是,我的代码一直在说:
.getParameterByName 不是函数
我的jQuery代码如下:
$(document).ready(function(){
var paramABC = $.getParameterByName('abc');
alert(paramABC);
});
(function ($) {
/* Gets value of querystring variable by name */
$.fn.getParameterByName = function (name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(('http://www.myexample.com/?abc=1&def=2').search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
};
}(jQuery));
请注意,我在上述函数中硬编码了location,因为 jsFiddle 在 URL 上没有查询字符串变量。该行的原始代码是:
results = regex.exec(location.search);
如果此代码有效,它将返回1(因为查询字符串中的abc=1)并在alert() 中显示它。我究竟做错了什么?谢谢。
【问题讨论】:
标签: javascript jquery jquery-plugins