任何人都可以告诉我为什么变量current和at不会传递给函数但是当我起诉控制台时出现正确的值?我对这一点完全无能为力,这意味着它必须简单!
records = [118571, 118666, 118693, 118791, 118827, 118942, 119041, 119144, 119265, 119310, 119430, 119570, 119617, 119726, 119762, 120030, 120086, 120103, 120129, 120145, 120219, 120365, 120441, 120562, 120607, 120932, 121072, 121232, 121260, 121667, 121725, 121764, 121876, 122007, 122008, 122009, 122131, 122458, 122804, 123081, 123156, 123239, 123320, 123413, 123624, 123715, 123842, 123953];
x = 48;
y = 48;
current = 123953;
function changerecord(change) {
var at = records.indexOf(current);
if (change == -1) {
var next = current;//current because we are going back one
var previous = records[at - 3];//-2 because we started on record and are moving 2 back
var moveto = records[at - 2];
x = x - 1;
document.getElementById("count").innerHTML = x + ' of ' + y;
alert("AT : " + at + "\n" + "Previous : " + previous + "\n" + "Next : " + next + "\n" + "x : " + x + "\n" + "y : " + y + "\n" + "moveto : " + moveto + "\n");
var current = moveto;
//document.getElementById('iframe_records').src='recordtemplate.php?flight=' + moveto;
}
else if (change == +1) {
var previous = current;//current because we are going back one
var next = records[at + 2];//-2 because we started on record and are moving 2 back
var moveto = records[at + 1];
x = x + 1;
alert("AT : " + at + "\n" + "Previous : " + previous + "\n" + "Next : " + next + "\n" + "x : " + x + "\n" + "y : " + y + "\n" + "moveto : " + moveto + "\n");
document.getElementById("count").innerHTML = x + ' of ' + y;
var current = moveto;
//document.getElementById('iframe_records').src='recordtemplate.php?flight=' + moveto;
}
}; // lookup
答案 0 :(得分:1)
你有一些范围和变量名称问题:
首先,尝试使用var
var records = [...]
var variable = ...
所以这在当前范围内是全局的,如果函数也在范围内,你也可以在函数中使用它。
您只是更改current
的值,而不是在函数范围内,您正在使用var current = ..
。使用其他名称,并不是有限的。
var test = 1;
function test() {
console.log(test); // Output: 1
var test = 2;
var oktopus = 8;
console.log(test); // Output: 2
console.log(oktopus); // Output: 8
}
console.log(test); // Output: 1
console.log(oktopus); // undefined oktopus
答案 1 :(得分:0)
您可以将current
作为参数传递,以避免此问题:
然后当你拨打changerecord
时,它会是这样的:
changerecord(change, 123953)
答案 2 :(得分:0)
您已为变量current
分配了一个值,但没有使用var
关键字声明它。执行此操作时,即为未声明的变量赋值,该变量将成为全局对象(即窗口)上的属性。
您应该知道的另一点是,当您声明一个与父函数作用域中另一个变量同名的局部变量时,最本地化的变量将用于内部函数作用域。
// ...
current = 123953; // Global variable
function changerecord(change) { // Local variable
var at = records.indexOf(current); // Local variable will be used
if (change==-1) // Also local one
{
var next = current; // Still local one!
// ...
请注意,window.current
应该有效。
答案 3 :(得分:0)
尝试:
$(document).ready(function(){
changerecord(change);
});