我正在用 JavaScript 构建一个滑块/推子。我通过这样声明一个对象,以一种我以前从未真正使用过它的方式使用 JavaScript:
var Object
{
// Statements & functions.
}
我在testing
从对象内部的函数 ( change_slide()
) 中检索对象内部变量 () 的值时遇到问题。我有这个代码:
var Fader =
{
// Fader properties.
speed: 1, // The time each interval will take.
fade: 0.1, // How much to change the slides opacity with each interval.
divs: ["fade_1", "fade_2", "fade_3"], // Array.
callbacks: [], // Array.
testing: 0123456798,
// Initialise fader.
initialise: function()
{
// Randomise the starting slide.
this.start_div = Math.floor((Math.random() * this.divs.length) + 1);
// Add pips and initialise display (block or none) for the slides.
for(var i = 0; i < this.divs.length; i++)
{
/*
* Create pips.
*/
var new_pip = document.createElement("div");
new_pip.className = "item";
new_pip.id = "pip_" + (1 + i);
document.getElementById("pips").appendChild(new_pip);
/*
* Get current div number.
*/
var extract_div_number = this.divs[i].replace("fade_", "");
if(extract_div_number == this.start_div)
{
//this.current_slide = extract_div_number;
document.getElementById("fade_" + extract_div_number).style.display = "block";
}
else
{
document.getElementById("fade_" + extract_div_number).style.display = "none";
}
}
this.pip_controller();
},
pip_controller: function()
{
for(var i = 0; i < this.divs.length; i++)
{
this.callbacks[i] = this.add_event("pip_" + (1 + i));
}
},
add_event: function(item)
{
if(window.addEventListener)
{
return document.getElementById(item).addEventListener("click", this.change_slide, false);
}
else
{
return document.getElementById(item).attachEvent("onclick", this.change_slide);
}
},
change_slide: function()
{
// Always returns "undefined" despite 'testing' being defined previously.
console.log(this.testing);
},
}
Fader.initialise();
// This works:
// Fader.change_slide();
这是我的 HTML:
<div id="main_slide">
<div id="fade_1"><h1>Slide 1</h1></div>
<div id="fade_2"><h1>Slide 2</h1></div>
<div id="fade_3"><h1>Slide 3</h1></div>
<div id="pips"></div>
</div>
为了记录,“点”是滑块底部的那些小圆圈,您可以单击以更改幻灯片。
那么,谁能告诉我为什么testing
返回undefined
,以及如何让我当前的代码检索 的实际值testing
?