gpt4 book ai didi

javascript - Polymer:使用 javascript 创建纸张复选框

转载 作者:行者123 更新时间:2023-12-03 06:43:32 24 4
gpt4 key购买 nike

我正在创建一个调查表单,该表单应该从 Json 对象中提出问题。到目前为止,我的代码可以运行,但我觉得我错过了一些 polymer 或 JS 函数的知识,这些知识可以让它变得更漂亮。截图:

enter image description here

脚本:

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>

最佳实践是什么?

最佳答案

解决方案是使用 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>

但是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>

关于javascript - Polymer:使用 javascript 创建纸张复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37845008/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com