如何解决如何在另一个文件的函数中使用文件中的函数中的变量
如您所见,我正在尝试使用一个文件中某个函数的变量计数器来另一个文件中的函数。我在函数中定义了计数器,但未以“ var”开头,我认为应使其成为全局变量。但是,这似乎不起作用。 SOS!
//function used in symptoms.html
function checkboxes(){
counter = parseInt(document.querySelectorAll('input[type="checkbox"]:checked').length); //counter would be a global var?
if (counter>=10){
location.href='end.html';
}else{
location.href='state.html';
}
}
//function used in another file
function statedegree(x){
var conclusion=x*counter;//uses counter var from checkboxes()
if (conclusion>=18){
location.href= 'end.html';
} else{
location.href='end1.html';
}
}
解决方法
可以使用localStorage API来实现不同页面上的持久性:
function checkboxes(){
localStorage.setItem('counter',document.querySelectorAll('input[type="checkbox"]:checked').length);
if (counter>=10){
location.href='end.html';
}else{
location.href='state.html';
}
}
function statedegree(x){
var conclusion=x * parseInt(localStorage.getItem('counter') || 0);
if (conclusion>=18){
location.href= 'end.html';
} else{
location.href='end1.html';
}
}
``
,
我不知道您文件的顺序,但是另一个文件必须包含在html中,该文件的第一个包含变量的声明。 同样,我认为声明该变量的函数必须在第二个函数之前调用。
否则,您可以使用window.counter将变量声明为跨多个文件的全局变量。
如果我错了请纠正我
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。