如何从 html 读取数组到 js

How to read array from html to js

本文关键字:数组 js 读取 html      更新时间:2023-09-26

>我声明了一个带有json数据的数组,然后当我init数组时,应该读取该数组并显示在div上。但是现在什么都不显示,谁能帮我检查我的代码,我犯了什么错误。谢谢。

JS小提琴

.HTML

<script>
$(function() {

    var array = [];
    array[0] = {
        "no": "1",
            "name": "fruit",
            "value": "mango",
            "totalvote": "75"
    };
    array[1] = {
        "no": "2",
            "name": "fruit",
            "value": "apple",
            "totalvote": "10"
    };
    array[2] = {
        "no": "3",
            "name": "fruit",
            "value": "orange",
            "totalvote": "5"
    };
    array[3] = {
        "no": "4",
            "name": "fruit",
            "value": "banana",
            "totalvote": "45"
    };
    PG.init("popup_survey_whitebox_selection", "1", array);
    PG.callpopup();
    PG.render_1();
});
</script>

.JS

    var PG = {
    divid: "",
    multiselection: "",
    optionitem: [],
    /*  type:"",        */
    init: function (divid, multiselection, optionitem) {
        /*     PG.type = type;*/
        PG.divid = divid;
        PG.multiselect = multiselection;
        PG.optionitem = optionitem;
    },
    test: function () {
        for (var i = 0; PG.optionitem.length > i; i++) {
            alert(PG.optionitem[i].name);
        }
    },
    callpopup: function () {
        $("#popup_survey_whitebox_content").hide();
        var orig = '', // create var to cache the original text
            newText = ''; // create var to cache the new Text with "..."
        $("label#popup_survey_label_title").text(function (index, currentText) {
            orig = currentText;
            newText = currentText.substr(0, 30);
            if (currentText.length > 30) newText += "...";
            return newText;
        });
        $("#popup_survey_whitebox").hover(function () {
            $('#popup_survey_whitebox_content').stop().animate({
                opacity: 1,
                height: "toggle"
            }, 500, function () {
                $("label#popup_survey_label_title").text(orig); // Here put the original text.
            }).css('position', 'relative');
        }, function () {
            $('#popup_survey_whitebox_content').stop().animate({
                opacity: 1,
                height: "toggle"
            }, 500, function () {
                $("label#popup_survey_label_title").text(newText); // Here put the new text with "..."
            }).css('position', 'relative');
        });
        $("#popup_survey_end_whitebox").click(function () {
            $("#popup_survey_whitebox").remove();
        });

    },
    render_1: function () {
        $.each(array, function (i, obj) {
            if (PG.multiselect == 1) {
                var selection = "<li class='popup_survey_whitebox_li'></li><input class='the_checkbox' type='radio' id=" + obj.value + " name=" + obj.name + " value=" + obj.value + ">" +
                    "<label class='popup_survey_whitebox_label' for=" + obj.value + ">" + obj.no + ". " + obj.value + "</label>" +
                    "<div class='popup_survey_whitebox_progressbar'><div class='popup_survey_whitebox_progressbar_inner' for=" + obj.value + " style='width:" + obj.totalvote + "%;'>" +
                    "</div></div>" +
                    "<div id='popup_survey_whitebox_percent' class='popup_survey_whitebox_percent'>" + obj.totalvote + "%</div>";
            } else {
                var selection = "<li class='popup_survey_whitebox_li'></li><input class='the_checkbox' type='checkbox' id=" + obj.value + " name=" + obj.name + " value=" + obj.value + ">" +
                    "<label class='popup_survey_whitebox_label' for=" + obj.value + ">" + obj.no + ". " + obj.value + "</label>" +
                    "<div class='popup_survey_whitebox_progressbar'><div class='popup_survey_whitebox_progressbar_inner' for=" + obj.value + " style='width:" + obj.totalvote + "%;'>" +
                    "</div></div>" +
                    "<div id='popup_survey_whitebox_percent' class='popup_survey_whitebox_percent'>" + obj.totalvote + "%</div>";
            }
            $("#" + PG.divid).append(selection);

        });
        var survey_button = "<br><input id='submit_btn' type='button' class='whiteboxbutton whiteboxbutton-small' value='Finish' style='width:100%;'>";
        $("#popup_survey_label_title").append("What is your favorite fruit??What is your favorite fruit??");
        /*$("#popup_survey_whitebox_title").append();*/
        $("#popup_survey_whitebox_inner_title").append("Please select 1 fruit only:");
        $('#popup_survey_whitebox_button').append(survey_button);

        $('.the_checkbox').on('change', function (evt) {
            $('.popup_survey_whitebox_percent').css('display', 'block');
            $('.popup_survey_whitebox_progressbar').css('display', 'block');
            $(".popup_survey_whitebox_button").show();
            if ($(this).siblings(':checked').length >= PG.multiselect) {
                this.checked = false;
            }
        });
    },

    save: function () {}
}

我控制台并收到此错误未捕获的引用错误:数组未定义,但我必须在 html 上声明。

除了closure之外,还有其他方法可以解决此错误。由于您已经在PG中存在optionitem并且您已经将optionitem传递给它,因此您也可以在方法render_1中使用它。

改变

$.each(array, function (i, obj) {

$.each(PG.optionitem, function (i, obj) {

这样,您就不需要将array定义为可能与其他变量冲突的全局变量。

http://jsfiddle.net/5qnhcudp/2/

您的数组处于闭包状态。你可以做一些不同的事情,但简单地说,你可以将数组声明移到闭包之外。

JSFiddle

<script>
var array = [];
$(function() {
    ...
});
</script>

找到了问题的另一个解决方案,您的PG对象实际上是在不需要的地方尝试引用全局范围。看,你声明数组的内联脚本,你正在将其传递到PG对象中。

你有这个:

render_1: function () {
    $.each(array, function (i, obj) {
        ...
    });
}

替换为:

render_1: function () {
    $.each(PG.optionitem, function (i, obj) {
        ...
    });
}

这个解决方案实际上独立于我的第一个解决方案。如果不希望数组在全局范围内,此解决方案将起作用。