我正在尝试从 javascript 对象访问数据,以便使用适当的信息动态填充 div。在我的示例中,教程中有三个步骤。当用户完成每个步骤时,他们单击按钮继续下一步。我希望在单击时调用函数“getStepData(stepNumber)”,并将步骤号传递到函数中并在我在 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)" />