【问题标题】:How to create a foreach loop to place syllables in each input of their respective word如何创建一个 foreach 循环以将音节放置在其各自单词的每个输入中
【发布时间】:2018-06-27 12:44:09
【问题描述】:

我有一个带有一个word 和4 个syllables 的练习块。在我的 json 中,它看起来像这样:

{
"main_object": {
"id": "new",
"getExerciseTitle": "TestFrontEnd",
"language": "nl_NL",
"application": "lettergrepen",
"main_object": {
  "title": "TestFrontEnd",
  "language": "nl_NL",
  "exercises": [
    {
      "word": "huisarts",
      "syllables": [
        "Huis",
        "arts",
        "",
        ""
      ]
    },
    {
      "word": "voetbal",
      "syllables": [
        "Voet",
        "bal",
        "",
        ""
      ]
    }
  ]
},
"dataType": "json"
 }
}

我想遍历这些wordsyllables,但每个word 都必须在一个练习块中与它们的syllables 保持一致。现在这就是我尝试这样做的方式,但我失败了很多次:

$(document).ready(function () {
$.getJSON('json_files/jsonData_' + ID + '.json', function(json) {


 var exercisetitle = json.main_object.getExerciseTitle;
    $("#getExerciseTitle").val(exercisetitle);


 var exercise = json.main_object.main_object.exercises;
    $.map(exercise, function(exercise, i) {
        $("#addOpdracht").click();
        $(".exerciseGetWordInput_" + i).val(exercise.word) 
         console.log(exercise.syllables);
          $(".sylll" + i).val(exercise.syllables)
    });

  });

});

为了给你可视化它,它应该看起来像这样

但它看起来像这样

那么我该怎么做才能得到我想要的结果呢?

编辑:我创建音节输入和练习输入的功能:

// This is the function that creates the exercise inputs 
function getWordInput(id, cValue) {
 cValue = cValue || '';
 var wInput = $('<input/>', {
'class': 'exerciseGetWordInput_' + id + ' form-group form-control ExerciseGetWordInput',  
'type': 'text',
'name': 'question_takeAudio_exerciseWord['+ exerciseAudioInput +']',
'placeholder': 'Exercise',
'id': 'exerciseGetWordInput',
'required': true
 });
 return wInput;
}


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

【问题讨论】:

  • 了解exerciseGetWordInput_sylll 的设置方式会有所帮助。似乎应该是每个练习的练习GetWordInput_1,然后是 syll_1_1syll_1_2syll_1_3syll_1_4(第一个数字代表练习,第二个数字代表音节)。这样您就可以轻松地将练习和音节保持在一起
  • 您可能还需要另一个循环来遍历练习中的音节数组。

标签: javascript jquery


【解决方案1】:

我不知道您是如何设置 HTML 的,但这应该可以帮助您朝着正确的方向开始。

我没有使用 $.map,因为它看起来不像您想要一个 new 数组,而是要对您当前的数组做一些事情。所以我转而使用 forEach(function(item, index) { .. }) 数组函数中内置的 Javascripts。但是,我使用的是Arrow function 版本。

我最后还使用了Template Literals 来使创建 jQuery 选择器更加简洁。

const exercises = [{
    "word": "huisarts",
    "syllables": [
      "Huis",
      "arts",
      "",
      ""
    ]
  },
  {
    "word": "voetbal",
    "syllables": [
      "Voet",
      "bal",
      "",
      ""
    ]
  }
];
// forEach((exercise, index) => { .. }) is shorthand for
// forEach(function(exercise, index) { .. });
// See ES6 arrow functions
exercises.forEach((exercise, index) => {
  const word = exercise.word; // Grab the word - huisarts/voetbal
  const syls = exercise.syllables; // Grab the syllables array
  const container = $(`.word-${index+1}`); // Get the correct container based on our index(index)
  const docContainer = document.querySelector(`.word-${index+1}`);
  $('.word', container).val(word); // Assign the word to the first input
  // Foreach syllable
  syls.forEach((syl, i) => {
    $('.syl', container).eq(i).val(syl); // Assign the syllable to the correct input based on our index(i)
    docContainer.querySelectorAll('.syl')[i].value = syl;
  });
});
table,
tr {
  width: 100%;
}

td {
  width: 50%;
  padding: 0 10px;
}

.word-1 input,
.word-2 input {
  display: block;
  width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table>
  <tr>
    <td class="word-1">
      <input class="word">
      <input class="syl">
      <input class="syl">
      <input class="syl">
      <input class="syl">
    </td>
    <td class="word-2">
      <input class="word">
      <input class="syl">
      <input class="syl">
      <input class="syl">
      <input class="syl">
    </td>
  </tr>
</table>

编辑

使用 jQuery 编写选择器很容易,并且相同的选择器可以与 Element 的 querySelector/querySelectorAll 函数一起使用。

$('.selector') 变为 document.querySelector('.selector')

在上面的sn-p中进行反射:

// const container = $(`.word-${index}`) becomes
const container = document.querySelector(`.word-${index}`);
..
// $('.word', container).val(word) becomes:
container.querySelector('.word').value = word;
..
// $('.syl', container).eq(i).val(syl) becomes:
container.querySelectorAll('.syl')[i].value = syl;

在 jQuery 中创建元素也更容易一些:

var TT = 0;

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

$('body').append(getWordPartInput(1, 1));

function getWordPartInput(id, cValue) {
  cValue = cValue || '';
  var wpInput = document.createElement('input');
  wpInput.classList.add('form-group', 'form-control', 'syllable', 'sylll', TT++);
  wpInput.type = 'text';
  wpInput.value = cValue;
  wpInput.placeholder = 'Syllables';
  wpInput.name = 'Syllablescounter[' + id++ + ']';
  return wpInput;
}

document.body.append(getWordPartInput(1, 2));

至于放弃 jQuery 的 ajax 以支持 vanilla JS this answer 很好地解释了。

【讨论】:

  • 我编辑了帖子,以便您更好地了解它,我并没有真正使用 HTML 来创建输入字段或任何东西。我尽量用 jquery 和 javascript 来做这件事。我希望我在所做的编辑中提供了足够的信息。另外,是否可以不使用 ajax/libs.jquery 的脚本?这会碰到我网站的其他功能。我仍然很欣赏你刚刚投入的大量工作。所以非常感谢@Wild Beard
  • @JJShaw 您不必使用 jQuery,但它让生活变得更轻松。特别是在创建新元素时。我使用的唯一 jQuery 是 $('selector').eq(index),无需 jQuery 即可轻松完成。至于不使用 jQuery 的 ajax - 你可以,但同样,它让生活变得轻松多了。至于结帐this post
  • 不是说你的代码有缺陷或任何东西,这很可能是我的错......但我似乎得到:“Uncaught TypeError: Cannot read property 'querySelector' of null”每当我尝试使用代码。你/你有时间澄清一下你的代码吗?我可以向您展示我尝试过的内容,但这会使原始帖子变得一团糟。所以是的。我仍然非常感谢您的努力
  • @JJShaw 听起来像 document.querySelector 失败了。确保正确拼写 documentdocument 是全球性的,因此您应该可以在代码中的任何位置使用它。我还更新了我的 sn-p 以显示 jQuery 和 document 的使用正常。
猜你喜欢
  • 2023-03-22
  • 1970-01-01
  • 2011-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-14
相关资源
最近更新 更多