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
か?