div に適切な情報を動的に入力するために、javascript オブジェクトからデータにアクセスしようとしています。私の例では、チュートリアルに 3 つのステップがあります。ユーザーが各ステップを終了したら、ボタンをクリックして次のステップに進みます。関数「getStepData(stepNumber)」を onclick と呼び、ステップ番号を関数に渡して、javascript で作成している html で使用したいと思います。サンプルコードはここにありますが、半分は jsFiddle で動作しています:
http://jsfiddle.net/enajenkins/xvFeX/24/
//create data object that will hold all data to be accessed later.
var tutorialDataObj = {
//define the tutorial container
profilePageTutorials: {
//define the steps and their data
step1: {
id: "tip1",
class: "profile_tip",
title: "Step 1",
subtitle: "How to edit your profile"
},//END: step1
step2: {
id: "tip2",
class: "search_tip",
title: "Step 2",
subtitle: "How to search"
},//END: step2
step3: {
id: "tip3",
class: "change-photo_tip",
title: "Step 3",
subtitle: "How to upload a new photo"
}//END: step3
}//END: profileTutorial
}//END: tutorialDataObj
//identify the div container that the dynamic html will be written into
var tutorialWindow = document.getElementById("tutorial-step-window");
//shorten the path to the data in the object
var tutorials = tutorialDataObj.profilePageTutorials;
//loop through each step in the data object
for ( var step in tutorials ) {
//build the html to be inserted dynamically using data from object
var html = ["<h2 id='title'>" + tutorials.step1.title + "</h2>" +
"<h3>" + tutorials.step1.subtitle + "</h3>"];
//insert the html into the div container
tutorialWindow.innerHTML = html;
alert(tutorials[step].subtitle);
}
function getStepData (stepNumber) {
alert(stepNumber); //here, I'm trying to access the argument from the input button. I'd like to pass it into the html I'm building above so I can access the data from the intended step when the user clicks the button.
}
ここにhtmlがあります:
<div id="tutorial-step-window" class="tip">HOWDY</div>
<input type="button" value="Change Data" onclick="getStepData(3)" />