每次调用函数时创建一个对象

时间:2016-08-11 07:02:29

标签: javascript html json

Codepen with my working application

我有以下内容:

    <button onClick="createBox()" id="box">Create Box</button>

这是我的功能:

function createBox()
    {
        var obj = {
        "1": "",
        "12": "",
        "123": "",
        "1234": "",
        "12345": "",
        "123456": ""
    };  
    console.log(obj)

        document.getElementById("box").onclick = function () {

            var div = document.createElement('div');
            div.className = 'new-box';       
            document.getElementsByTagName('body')[0].appendChild(div);

        }
    }

每次点击按钮,我想创建一个带有新对象的新框。之后,我想点击一个框并用我的选择列表填充该对象框:

<select id="asdf" class="selectVal">
    <option value="1">asdf</option>
    <option value="2">asdf1</option>
    <option value="3">asdf2</option>
</select>

<select id="asdf" class="selectVal">
    <option value="1">asdf1</option>
    <option value="2">asdf2</option>
    <option value="3">asdf3</option>
    <option value="4">asdf4</option>
</select>

<select id="asdf" class="selectVal">
    <option value="1">asdf1</option>
    <option value="2">asdf2</option>
    <option value="3>asdf3</option>
    <option value="4">asdf4</option>
    <option value="asdf5>asdf5</option>
    <option

我有以下代码来填充对象:

    function getSelectedItems() {
        var elements = document.querySelectorAll('.selectVal, input');
        var results = {};

        for (var i = 0; i < elements.length; i++) {
            var element = elements[i];
            var strSel = '';
            if (element.tagName == 'SELECT'){
                strSel = element.options[element.selectedIndex].text;
            }
            else if (element.tagName == 'INPUT'){
                strSel = element.value;
            }

            results[element.id] = strSel;
            console.log(results)
        }


        strSel = JSON.stringify(results, null, 4);
        var blob = new Blob([strSel], {type: "application/json"});
        var url  = URL.createObjectURL(blob);

        var a = document.createElement('a');
        a.download    = "file.json";
        a.href        = url;
        a.textContent = "Download JSON";

        console.log(strSel);
        document.getElementById('json').innerHTML = strSel;
        document.getElementById('download').appendChild(a);

所以我需要调整我的代码来创建具有独立对象的独立框,我可以通过我的选择和输入来填充以下载JSON。

0 个答案:

没有答案