循环获取1个输入字段中的所有单词

时间:2018-06-26 09:36:51

标签: javascript jquery

如下图所示,我的单词“ es”和“ presso”被放在一个输入字段中,而不是在一个输入字段中是“ es”,在另一个输入字段中是“ presso”。 enter image description here

我的JSON的样子:

{
"main_object": {
"id": "new",
"getExerciseTitle": "Example",
"language": "nl_NL",
"application": "lettergrepen",
"main_object": {
  "title": "Example",
  "language": "nl_NL",
  "exercises": [
    {
      "word": "espresso",
      "syllables": [
        "es",
        "presso",
        "",
        ""
      ]
    }
  ]
},
"dataType": "json"
}
}

这是我的循环的样子:

$.map(exercise, function(exercise, i) {
$("#addOpdracht").click();
$(".exerciseGetWordInput_" + i).val(exercise.word) // starts with 0

var exerSyll = json.main_object.main_object.exercises;

$.map(exerSyll, function(exer, s) {
 console.log(exer.syllables);

$(".syllable" + s).val(exer.syllables);
});

});

放大我获取syllables的循环:

  var exerSyll = json.main_object.main_object.exercises;

$.map(exerSyll, function(exer, s) {
 console.log(exer.syllables);

$(".syllable" + s).val(exer.syllables);
});

我创建syllable inputs的函数:

function getWordPartInput(id, cValue){
 cValue = cValue || '';
 var wpInput = $('<input/>', {
'class': 'form-group form-control syllable' + SyllablesID++,
'type': 'text',
'value': cValue,
'placeholder': 'Syllables',
'name': 'Syllablescounter['+ SyllablesID++ +']'
 });
 return wpInput;
}

我做错了什么? (我确实声明了变量SyllablesID,所以不用担心那部分。)

1 个答案:

答案 0 :(得分:1)

var data = {
"main_object": {
"id": "new",
"getExerciseTitle": "Example",
"language": "nl_NL",
"application": "lettergrepen",
"main_object": {
  "title": "Example",
  "language": "nl_NL",
  "exercises": [
    {
      "word": "espresso",
      "syllables": [
        "es",
        "presso",
        "",
        ""
      ]
    }
  ]
},
"dataType": "json"
}
};


function draw(data){
  
  for (ex of data.main_object.main_object.exercises){
       for( sy of ex.syllables){
         $("#container").append(`<input type="text" value="${sy}">`)
       }
  }
}

draw(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="container"><div>

syllables是按照发布的JSON的数组,因此您必须获取每个值并将其作为值添加到输入元素。您可以再次使用.mapfor/forEach等循环遍历教学大纲数组并将数组条目添加到输入值中

$.map(exerSyll, function(exer, s) {
 console.log(exer.syllables);

 $.map(exer.syllables, function(syll, i){
   $(".syllable" + i).val(syll);
})

});