[英]Check a value from Array in javascript?
我有一个:
var pageURL = location.href; // stores the URL of the current page in the var pageURL
我有 :
var Page = Array ();
page [0] = "http://web1.com"
page [1] = "http://web2.com"
page [2] = "http://web3.com"
现在,我想制作一个函数(称为nextPage)来检查数组中这些页面中的哪一个等于PageURL。 另外,我还需要一个按钮,因此单击该按钮将带我进入下一页。 那意味着我想将页面增加1。
您可以非常简单地使用
var current = page.indexOf(location.href);
然后转到下一页
location.href = page[current + 1];
var form = document.createElement('form');
form.id = "nextForm";
document.body.appendChild(form);
var nextButton = document.createElement('input');
nextButton.type = 'button';
nextButton.id = 'nextButton';
nextButton.value = 'Next Button';
nextButton.onclick = nextPage;
form.appendChild(nextButton);
function nextPage() {
var page = Array ();
page[0] = "http://web1.com" // insert your urls here
page[1] = "http://web2.com"
page[2] = "http://web3.com"
var matchIndex = page.indexOf(location.href);
var nextIndex;
if (matchIndex !== -1 && page[matchIndex + 1]) {
nextIndex = matchIndex + 1;
} else {
alert("You're at the last page"); // next page in the array does not exist, you can handle the error however you want
return;
}
goToNextPage(page[nextIndex]);
}
function goToNextPage(url) {
document.location.href=url;
}
根据约瑟夫的回答,完整的代码如下所示:
function goToNextPage() {
var currentPageUrl = location.href;
var pageUrls = [
"http://web1.com",
"http://web2.com",
"http://web3.com"
];
var currentIndex = pageUrls.indexOf(location.href);
var nextIndex = currentIndex + 1;
var nextPageUrl = pageUrls[nextIndex];
location.href = nextPageUrl;
}
另外,如果在IE中对indexOf的支持是您遇到的问题,请从另一个StackOverflow问题中找出答案: 如何为Internet Explorer浏览器修复JavaScript中的Array indexOf()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.