>我有一个示例代码:
function getKeyword() {
var instance = this;
var googlePattern = /(www.google..*)/;
this.params = function(parameters) {
var result = [];
var params = parameters.split("&");
for(var p in params) {
var kv = params[p].split("=");
result[kv[0]] = kv[1];
}
return result;
};
this.googleKeywords = function(params){
var query = params["q"];
var pattern = /"(.*?)"|(w+)/g;
return decodeURIComponent(query).replace(/+/g, " ").match(pattern);
};
this.parseReferrer = function(){
var result = [];
var pathAndParams = document.referrer.split("?");
if(pathAndParams.length == 2) {
var path = pathAndParams[0];
var params = this.params(pathAndParams[1]);
if(path.search(googlePattern) > 0) {
result = this.googleKeywords(params);
}
}
return result;
};
return this.parseReferrer();
}
然后:
<script type="text/javascript">
if (document.referrer && document.referrer != "") {
if (document.referrer.search(/google.*/i) != -1){
var keyword = getKeyword();
alert(keyword);
} else {
alert('Not search from google');
}
} else {
alert('Not referrer');
}
</script>
例如:当我使用关键字搜索"iphone 5"时,结果未显示警报("iphone 5")?如何解决?
JavaScript
for in
构造循环不仅仅是数组中的条目。如果要使用for in
则需要确保仅处理实际参数。通过检查hasOwnProperty
最简单的方法是:
this.params = function(parameters) {
var result = [];
var params = parameters.split("&");
for(var p in params) {
if (params.hasOwnProperty(p))
{
var kv = params[p].split("=");
result[kv[0]] = kv[1];
}
}
return result;
};
或者,您可以在数组上使用常规for
循环:
this.params = function(parameters) {
var result = [];
var params = parameters.split("&");
for(var i=0; i < params.length; i++) {
var kv = params[i].split("=");
result[kv[0]] = kv[1];
}
return result;
};