javascript - 如何在 JSON 文件中添加图像?

标签 javascript jquery html css json

基本上,我有一个表单可以询问简单的问题,用户可以在选择、文本框或文本区域中回答。

我使用 JSON 来解析问题。

但是我需要知道如何在问题上方插入图像,如下所示: http://prntscr.com/f5o8fc

这是我的 jQuery:

survey = { questions: undefined,
           firstQuestionDisplayed: -1,
           lastQuestionDisplayed: -1};

(function (survey, $) {

    survey.setup_survey = function(questions) {
        var self = this;
        this.questions = questions;

        this.questions.forEach(function(question) {
            self.generateQuestionElement( question );
        });

        $('#backBtn').click(function() {
            if ( !$('#backBtn').hasClass('disabled') ) {
                self.showPreviousQuestionSet();
            }
        });

        $('#nextBtn').click(function() {
            var ok = true;
            for (i = self.firstQuestionDisplayed; i <= self.lastQuestionDisplayed; i++) {
                if (self.questions[i]['required'] === true && !self.getQuestionAnswer(questions[i])) {
                    $('.question-container > div.question:nth-child(' + (i+1) + ') > .required-message').show();
                    ok = false;
                }
            }
            if (!ok)
                return

            if ( $('#nextBtn').text().indexOf('Continue') === 0 ) {
                self.showNextQuestionSet();
            }
            else {
                var answers = {res: $(window).width() + "x" + $(window).height()};
                for (i = 0; i < self.questions.length; i++) {
                    answers[self.questions[i].id] = self.getQuestionAnswer(self.questions[i]);
                }

                $.ajax({type: 'post',
                        url: 'http://localhost:7000/answers',
                        contentType: "application/json",
                        data: JSON.stringify(answers),
                        processData: false,
                        success: function(response) {
                            self.hideAllQuestions();
                            $('#nextBtn').hide();
                            $('#backBtn').hide();
                            if ('success' in response) {
                                $('.completed-message').html('Thank you for participating in this survey!<br><br>'+response['success']);
                            }
                            else if ('error' in response) {
                                $('.completed-message').text('An error occurred: '+response['error']);
                            }
                            else {
                                $('.completed-message').text('An unknown error occurred.');
                            }
                        },
                        error: function(response) {
                            self.hideAllQuestions();
                            $('#nextBtn').hide();
                            $('#backBtn').hide();
                            $('.completed-message').text('An error occurred: could not send data to server');
                        }
                });
            }
        });

        this.showNextQuestionSet();

    }

    survey.getQuestionAnswer = function(question) {
        var result;
        if ( question.type === 'single-select' ) {
            result = $('input[type="radio"][name="' + question.id + '"]:checked').val();
        }
        else if ( question.type === 'single-select-oneline' ) {
            result = $('input[type="radio"][name="' + question.id + '"]:checked').val();
        }
        else if ( question.type === 'text-field-small' ) {
            result = $('input[name=' + question.id + ']').val();
        }
        else if ( question.type === 'text-field-large' ) {
            result = $('textarea[name=' + question.id + ']').val();
        }
        return result ? result : undefined;
    }

    survey.generateQuestionElement = function(question) {
        var questionElement = $('<div id="' + question.id + '" class="question"></div>');
        var questionTextElement = $('<div class="question-text"></div>');
        var questionAnswerElement = $('<div class="answer"></div>');
        var questionCommentElement = $('<div class="comment"></div>');
        questionElement.appendTo($('.question-container'));
        questionElement.append(questionTextElement);
        questionElement.append(questionAnswerElement);
        questionElement.append(questionCommentElement);
        questionTextElement.html(question.text);
        questionCommentElement.html(question.comment);
        if ( question.type === 'single-select' ) {
            questionElement.addClass('single-select');
            question.options.forEach(function(option) {
                questionAnswerElement.append('<label class="radio"><input type="radio" value="' + option + '" name="' + question.id + '"/>' + option + '</label>');
            });
        }
        else if ( question.type === 'single-select-oneline' ) {
            questionElement.addClass('single-select-oneline');
            var html = '<table border="0" cellpadding="5" cellspacing="0"><tr><td></td>';
            question.options.forEach(function(label) {
                html += '<td><label>' + label + '</label></td>';
            });
            html += '<td></td></tr><tr><td><div>' + question.labels[0] + '</div></td>';
            question.options.forEach(function(label) {
                html += '<td><div><input type="radio" value="' + label + '" name="' + question.id + '"></div></td>';
            });
            html += '<td><div>' + question.labels[1] + '</div></td></tr></table>';
            questionAnswerElement.append(html);
        }
        else if ( question.type === 'text-field-small' ) {
            questionElement.addClass('text-field-small');
            questionAnswerElement.append('<input type="text" value="" class="text" name="' + question.id + '">');
        }
        else if ( question.type === 'text-field-large' ) {
            questionElement.addClass('text-field-large');
            questionAnswerElement.append('<textarea rows="8" cols="0" class="text" name="' + question.id + '">');
        }
        if ( question.required === true ) {
            var last = questionTextElement.find(':last');
            (last.length ? last : questionTextElement).append('<span class="required-asterisk" aria-hidden="true">*</span>');
        }
        questionAnswerElement.after('<div class="required-message">This is a required question</div>');
        questionElement.hide();
    }

    survey.hideAllQuestions = function() {
        $('.question:visible').each(function(index, element){
            $(element).hide();
        });
        $('.required-message').each(function(index, element){
            $(element).hide();
        });
    }

    survey.showNextQuestionSet = function() {
        this.hideAllQuestions();
        this.firstQuestionDisplayed = this.lastQuestionDisplayed+1;

        do {
            this.lastQuestionDisplayed++;  
            $('.question-container > div.question:nth-child(' + (this.lastQuestionDisplayed+1) + ')').show();
            if ( this.questions[this.lastQuestionDisplayed]['break_after'] === true)
                break;
        } while ( this.lastQuestionDisplayed < this.questions.length-1 );

        this.doButtonStates();
    }

    survey.showPreviousQuestionSet = function() {
        this.hideAllQuestions();
        this.lastQuestionDisplayed = this.firstQuestionDisplayed-1;

        do {
            this.firstQuestionDisplayed--;  
            $('.question-container > div.question:nth-child(' + (this.firstQuestionDisplayed+1) + ')').show();
            if ( this.firstQuestionDisplayed > 0 && this.questions[this.firstQuestionDisplayed-1]['break_after'] === true)
                break;
        } while ( this.firstQuestionDisplayed > 0 );

        this.doButtonStates();
    }

    survey.doButtonStates = function() {
        if ( this.firstQuestionDisplayed == 0 ) {
            $('#backBtn').addClass('invisible');  
        }
        else if ( $('#backBtn' ).hasClass('invisible') ) {
            $('#backBtn').removeClass('invisible');
        }

        if ( this.lastQuestionDisplayed == this.questions.length-1 ) {
            $('#nextBtn').text('Finish');
            $('#nextBtn').addClass('blue');  
        }
        else if ( $('#nextBtn').text() === 'Finish' ) {
            $('#nextBtn').text('Continue »'); 
            $('#nextBtn').removeClass('blue');
        }
    }
})(survey, jQuery);


$(document).ready(function(){
    $.getJSON('questions.json', function(json) {
        survey.setup_survey(json);        
    });
});

window.onbeforeunload = function() {
    return "This will reset all answers that you've already filled in!";
}

从这里开始:

我解析我的 JSON 文件:

[  
    {  
        "text":"Do you know me?",
        "id":"2",
        "break_after":true,
        "required":true,
        "type":"single-select",
        "options":[  
            "YES",
            "NO"
        ]
    },
    {  
        "text":"What gets wetter and wetter the more it dries?",
        "id":"3",
        "break_after":true,
        "required":true,
        "type":"single-select",
        "options":[  
            "a car",
            "a towel",
            "a plane",
            "a television"
        ]
    },
    {  
        "text":"Are you going to?",
        "id":"4",
        "type":"text-field-small"
    },
    {  
        "text":"What goes up and down the stairs without moving?",
        "id":"5",
        "type":"single-select",
        "options":[  
            "a toddler",
            "an arrow",
            "towels",
            "a rug"
        ]
    },
    {  
        "text":"What can you catch but not throw?",
        "id":"6",
        "type":"single-select",
        "options":[  
            "a couch",
            "a cold",
            "a puppy",
            "a baseball"
        ]
    },
    {  
        "text":"I can run but not walk. Wherever I go, thought follows close behind. What am I?",
        "id":"7",
        "type":"single-select",
        "options":[  
            "a doctor",
            "a pineapple",
            "a nose",
            "pimples"
        ]
    },
    {  
        "text":"What's black and white and red all over?",
        "id":"8",
        "type":"single-select",
        "options":[  
            "an embarrased skunk",
            "a turtle",
            "a giraffe",
            "a dog"
        ]
    },
    {  
        "text":"What goes around the world but stays in a corner?",
        "id":"9",
        "type":"single-select",
        "options":[  
            "a stamp",
            "coffee",
            "a dog",
            "plants"
        ]
    }
]

这是 HTML 的样子:

<div class="main">

<div><h1 class="title">Test Questionaire</h1><br>

<div class="question-container"></div>
<a id="backBtn" href="#" class="button">« Back</a>
<a id="nextBtn" href="#" class="button">Continue »</a>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="survey.js" type="text/javascript"></script>

</div><div class="completed-message"></div>
</div></div>

有什么想法吗?

最佳答案

实现此目的的一种方法是使用像 WebSemantics Image to DataURL converter 这样的网站创建所需图像的数据字符串表示。因为这是一个字符串,它可以存储在一个 JSON 文件中,并在获取和解析后作为 HTML img 标记的 src 属性插入,就像这样......

/* JSON example */
{
    "text": "Some text blah blah...",
    "img": "data:image/png;base64,iVBORw0KGgoAAA..."
}

/* Javascript example */
var obj = theParsedJSON;

var img = '<img src="'+obj.img+'" />';
element.innerHTML = img;

……或者……

var img = new Image();

img.addEventListener('load', function() {
    /* do something with 'this' image: EG */
    element.appendChild(this);
}, false);

img.src = obj.img;

唯一要记住的是图像数据 URL 可以为您的 JSON 文件增加相当多的权重,因此对在线资源的绝对引用可能是更好的选择:EG...

{
    "text": "Some text blah blah...",
    "img": "http://domain.co/path/to/image.jpg"
}

希望对您有所帮助。 :)

关于javascript - 如何在 JSON 文件中添加图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43859379/

相关文章:

javascript - (x^2) 在 JavaScript 中做什么?

javascript - 如何为jstree中不同类型的节点配置上下文菜单?

javascript - Angular - 自定义过滤器是如何工作的?

javascript - 在ajax请求后重新加载div

javascript - 将页面的整个 html 内容向下移动?

jquery - 使用 jQuery 选择表中的下一个 <td>

asp.net - JavaScript 事件和回调

c# - 部分 View 上的 mvc4 分页

html - Markdown 中的内联 CSS

html - 右侧的 CSS 过渡 Logo