我想根据访问者URL中的变量重定向访问者。用例是有关重力形式的测验,其中用户将被重定向到example.com/processing?quizresult={n}
n
是数值(0-50)。
有3种可能的结果(0-15、16-30、31-50)。
我发现JavaScript会根据URL是否包含变量而不是变量范围进行重定向。有没有比50个“ IF”语句更好的方法?
<script>
if(document.location.href.indexOf('1') > -1) {
document.location.href = 'http://www.example.com/resultA';
}
if(document.location.href.indexOf('2') > -1) {
document.location.href = 'http://www.example.com/resultA';
}
if(document.location.href.indexOf('3') > -1) {
document.location.href = 'http://www.example.com/resultA';
}
尝试一下:
示例:
// extract {n} from example.com/processing?quizresult={n}
const getParamValue = (url, parameterKey) => {
const [urlWithoutParameters, parameters = ''] = url.split('?'); // ['example.com/processing', 'quizresult=1']
const paramsArr = parameters.split('&'); // ['quizresult=1']
for (let i = 0; i < paramsArr.length; i++) {
const [k, v] = paramsArr[i].split('='); // k = 'quizresult', v = '1'
if (k === parameterKey) {
return v;
}
}
};
// conditionally redirect to the result urls.
const conditionallyRedirect = (url) => {
const quizResult = getParamValue(url, 'quizresult');
if (quizResult >= 0 && quizResult < 16) {
console.log('resultA');
// document.location.href = 'http://www.example.com/resultA';
} else if (quizResult >= 16 && quizResult < 31) {
console.log('resultB');
// document.location.href = 'http://www.example.com/resultB';
} else if (quizResult >= 31 && quizResult <= 50) {
console.log('resultC');
// document.location.href = 'http://www.example.com/resultC';
}
// do not redirect otherwise
};
// Examples
conditionallyRedirect('example.com/processing?quizresult=1'); // redirects to resultA
conditionallyRedirect('example.com/processing?quizresult=17&someotherparam=whatever'); // redirects to resultB
conditionallyRedirect('example.com/processing'); // does not redirect
conditionallyRedirect('example.com/processing?quizresult=100'); // does not redirect
所以这对您有用:
conditionallyRedirect(document.location.href);
嘿,您的解决方案在这里,
尝试一下。
if (document.location.href.indexOf(1) > -1) {
alert("your url contains the name franky");
} else if (document.location.href.indexOf(2) > -1) {
alert("your url contains the name franky");
} else if (document.location.href.indexOf(3) > -1) {
alert("your url contains the name franky");
} else{ alert("not matach any value");}