我正在尝试获取url查询字符串参数并在if条件中进行比较。我在单个变量中获取这两个参数。 如何一起检查这两个参数。 任何人都可以告诉我如何比较网址的参数,例如:
http://www.xyz.com/?utm_campaign=freeship&utm_content=COUPON_CODE_HERE
我需要获取参数“freeship”和“COUPON_CODE_HERE” 请指教。
这是我的代码:
<script type="text/javascript">
$(document).ready( function(){
getUrlVars();
var param2 = [];
if( param2 =("percentoff " && "COUPON_CODE_HERE"))
{
alert("hi");
}
if( param2 = ("freeship " && "COUPON_CODE_HERE"))
{
alert("hello");
}
});
function getUrlVars()
{
var string1=["utm_campaign"];
var string2=["utm_content"];
var string1 = [], hash;
var string2 = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < string2.length; i++)
{
hash = string2[i].split('=');
string1.push(hash[0]);
string1[hash[0]] = hash[1];
param2=(hash[1]);
//alert(hash[1]);
}
return string1;
}
</script>
答案 0 :(得分:0)
试试这个
<script type="text/javascript">
$(document).ready( function(){
var params = getUrlVars();
var utm_campaign = params["utm_campaign"];
var utm_content = params["utm_content"];
if( utm_campaign === "percentoff" && utm_content == "COUPON_CODE_HERE")
{
alert("hi");
}
if( utm_campaign === "freeship" && utm_content === "COUPON_CODE_HERE")
{
alert("hello");
}
});
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
</script>
根据您的要求,这些是cookie操作的功能。
CreateCookie("cookie1", utm_campaign , 60);
//Creates client side cookie,
function CreateCookie(name, value, minutes) {
var expires = "";
if (minutes) {
var date = new Date();
date.setTime(date.getTime() + (minutes * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
document.cookie = name + "=" + value + expires;
}
//Read cookie value
function ReadCookie(name) {
var key = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(key) == 0) return c.substring(key.length, c.length);
}
return null;
}
//Remove cookie
function RemoveCookie(name) {
CreateCookie(name, "", -1);
}
答案 1 :(得分:0)
使用document.URL
或window.location.href
,您可以获取js中的链接
然后你可以使用匹配函数和正则表达式获取值:
var url = document.URL;
url="http://xyz.com/?utm_campaign=freeship&utm_content=COUPON_CODE_HERE"; // remove this line on the website
var campaign = url.match('utm_campaign=([^&]*)');
var content = url.match('utm_content=([^&]*)');
console.log(campaign[1]); // index 1 is the match between the brackets (the wanted value) as 0 will be the whole matched string
console.log(content[1]);
//if you want you can assign the values to other vars:
// var utm_campaign = campaign[1],utm_content = content[1];
// ** here you can compare campaign[1] & content[1] or utm_campaign & utm_content **