jquery解析并自动将嵌套的对象键和值插入到对应的div中

时间:2012-08-10 14:00:25

标签: javascript ajax jquery-ui jquery

我有以下对象示例:

"experience": {
    "1": {
        "jobtitle": "job_title",
        "companyname": "company_name",
        "companytown": "company_town",
        "companycountry": "company_country",
        "summary": "Summary",
        "exp_from_month": "August",
        "exp_from_year": "2009",
        "exp_to_year": "2009",
        "current_position": "false"
    },
    "2": {
        "jobtitle": "job_title",
        "companyname": "company_name",
        "companytown": "company_town",
        "companycountry": "company_country",
        "summary": "Summary",
        "exp_from_month": "August",
        "exp_from_year": "2009",
        "exp_to_year": "2009",
        "current_position": "false"
    }
}

var key =对象键 var val =对应值

我有一个像这个例子的HTML结构:

<div id='experience"+key+"'>
    <p>
        <strong>
            <textarea cols='30' rows='1' name='job_title"+key+"' style=''>+value+</textarea>
        </strong>&nbsp;
        <input type='checkbox' id='current_position"+key+"' checked="++value++">&nbsp;Current Position</p>
    <p>
        <textarea name='company_name"+key+"' cols='30' rows='1' style=''>"++value++"</textarea>
    </p>
    <p>
        <textarea name='company_town"+key+"' cols='30' rows='1' style=''>"++value++"</textarea>&nbsp;
        <textarea name='company_country"+key+"' cols='30'
        rows='1' style=''>"++value++"</textarea>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <a
        href='#' class='save_experience"+key+"' onclick='addexperience("+key+")'>Edit</a>
    </p>
    <p id='experince_dates"+key+"'>From:
        <select name='experience_from_month"+key+"' style='width:100px;'>
            <option>"++value++"</option>
        </select>&nbsp;
        <select name='experience_from_year"+key+"' style='width:100px;'>
            <option>"++value++"</option>
        </select>&nbsp;To:
        <select name=experience_to_month "+key+" ' style='width:100px;'>
            <option>August</option>
        </select>&nbsp;
        <select name='experience_to_year "+key+" ' style='width:100px; '>
            <option>2009</option>
        </select>&nbsp;
    </p>
    <p>
        <textarea name='experience_summary "+key+" ' rows='5 ' cols='120 ' style=''>Summary</textarea>
    </p>
</div>

如何才能使对象内的每个experience成为可能?

1 个答案:

答案 0 :(得分:2)

试试这个

for(var key in experience)
    $('body').append('<div id="experience' + key + '">' + experience[key].jobtitle + '</div>');