我正在为调查创建一个表单,该表单应该从Json对象中询问问题。 我的代码到目前为止工作,但我觉得我错过了一些聚合物或JS功能的知识,这将使它更美丽。 截图:
脚本:
var questions = [
{
"question": "What do you want for christmas?"
, "mode": "radio"
, "answers": ["Nintendo", "iPony", "You", "A tiny little Shotgun"]
}
];
console.log(questions);
function foo() {
var question = document.createElement('div');
question.className = 'question';
question.innerHTML = "Frage:" + questions[0].question;
console.log(question);
var surveyQuestions = document.getElementById("survey-questions");
surveyQuestions.appendChild(question);
var answers = document.createElement('div');
answers.className = "answers";
questions[0].answers.forEach(buildRadio);
surveyQuestions.appendChild(answers);
function buildRadio(item, index) {
var paperCheckbox = document.createElement('paper-checkbox');
var br = document.createElement('br');
paperCheckbox.setAttribute("name",item);
paperCheckbox.setAttribute("value",item);
paperCheckbox.getElementsByTagName('div')[1].innerHTML = item;
paperCheckbox.children[1].innerHTML = item;
answers.appendChild(paperCheckbox);
answers.appendChild(br);
}
}
我的问题的另一个小例子:
<div class="card"></div>
创建
<div class="card style-scope survey-app"></div>
但是
var card = document.createElement('div');
card.className = "card";
仅创建
<div class="card"></div>
什么是最佳做法?
答案 0 :(得分:1)
解决方案正在使用dom-repeat
,效果很好:
<template is="dom-repeat" items="{{questions}}">
<div class="card">
<div class="question">Frage {{index}}: {{item.question}}</div>
<template is="dom-if" if="{{_isCheckQuestion(item)}}">
<template is="dom-repeat" items="{{item.answers}}">
<paper-checkbox>{{item}}</paper-checkbox>
<br>
</template>
</template>
<template is="dom-if" if="{{_isRadioQuestion(item)}}">
<paper-radio-group>
<template is="dom-repeat" items="{{item.answers}}">
<paper-radio-button name="{{item}}">{{item}}</paper-radio-button>
<br>
</template>
</paper-radio-group>
</template>
</div>
</template>
&#13;
但是dom-if
有点棘手
<script>
Polymer({
is: 'survey-app'
, properties: {
prop1: {
type: String
, value: 'survey-app'
}
}
, ready: function () {
this.questions = [
{
"question": "What do you want for christmas?"
, "mode": "check"
, "answers": ["Nintendo", "iPony", "You", "A tiny little Shotgun"]
}
, {
"question": "Yes or no?"
, "mode": "radio"
, "answers": ["yes", "no"]
},
];
}
, _isCheckQuestion: function (question) {
return question.mode == 'check'
}
, _isRadioQuestion: function (question) {
return question.mode == 'radio'
}
});
</script>
&#13;