将onclick事件的参数传递到使用数据对象构建HTML的函数中——到目前为止在js中只完成了一半

Pass parameter from onclick event into function that builds HTML using data object - half working so far in jsfiddle

本文关键字:到目前为止 js 一半 函数 HTML 参数传递 事件 onclick 构建 对象 数据      更新时间:2023-09-26

我试图从javascript对象访问数据,以便动态地填充适当的信息的div。在我的例子中,教程中有三个步骤。当用户完成每个步骤后,他们单击按钮进入下一个步骤。我想函数"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)" />

试试这个…

http://jsfiddle.net/xvFeX/45/

我做这件事的方式和你描述的略有不同,但实现了同样的目标:

我删除了按钮上的内联click事件并添加了id。然后我在js中添加了click,并根据对象的步数进行了计数。