您可以在图片中看到,我有一个带有2个输入字段的单词,一个带有3个单词的单词。我如何制作一个变量,以检查带有2个输入字段的单词是否正确填写。例如:带有3的单词有3个输入字段,第一个应该输入1,第二个输入2,第三个输入3。如何使它们保留输入字段,直到正确填写所有3个输入字段,然后将3个输入字段更改为绿色按钮?应该对每个单词及其各自的输入字段进行此操作。现在我有这样的...但是这只会检查每个单词,然后将其变成绿色的输入按钮:
function prepareCheck() {
$.getJSON('json_files/jsonData_' + ID + '.json', function(json) {
var idxxx = 0;
$(document).on('change', '.syl-input', function() {
var rowCounter = $(this).parent().parent().parent().parent().attr('id');
var inputCounter = $(this).attr('id');
var jsyl = json.main_object.main_object.exercises[rowCounter].syllables[inputCounter];
var jsylall = json.main_object.main_object.exercises[rowCounter].syllables;
var valueInput = $(this).val();
if (valueInput == jsyl) {
var correctBtn = $('<button/>', {
'class': 'btn btn-success buttonCorrect',
'type': 'button',
'id': "button" + CBC++,
'html': valueInput
});
$(this).replaceWith(correctBtn);
S.playRight();
S.addRight();
} else if ($.inArray(valueInput, jsylall) >= -1) {
$(this).css({'color':'red'});
S.playWrong();
S.addWrong();
}
});
});
}
JSON的样子:
{
"main_object": {
"id": "new",
"getExerciseTitle": "testforcounter",
"language": "nl_NL",
"application": "lettergrepen",
"main_object": {
"title": "testforcounter",
"language": "nl_NL",
"exercises": [
{
"word": "Texel",
"syllables": [
"tex",
"el",
"",
""
]
},
{
"word": "3",
"syllables": [
"1",
"2",
"3",
""
]
}
]
},
"dataType": "json"
}
}
如何创建输入字段(以备不时之需)。
var sylInput = $('<input/>', {
'type': 'text',
'class': 'form-control syl-input',
'name': +c++,
'id': +idsyll++
});
答案 0 :(得分:0)
尝试以下代码:
function checkInputFields(key, value) {
const validFields = [];
for(var i = 0; i < key.length; i++) {
if (document.getElementById(key[i]).value == value[i]) {
validFields.push('true');
if (key.length === validFields.length) {
for (let k of key) {
// document.getElementById(k).style.backgroundColor = 'green';
// Use these 2 lines, if you want to change the input text fields to Bootstrap buttons
document.getElementById(k).setAttribute('type', 'button');
document.getElementById(k).className = 'btn btn-success';
}
}
}
}
}
// JSON
const json = {
row1: {
keys: ["row1-field1", "row1-field2"],
values: ['hello', 'world']
},
row2: {
keys: ['row2-field1', 'row2-field2', 'row2-field3'],
values: [1, 2, 3]
}
}
// Row1
const row1Keys = json.row1.keys;
const row1Values = json.row1.values;
// Row2
const row2Keys = json.row2.keys;
const row2Values = json.row2.values;
const inputs = document.querySelectorAll('input[type=text]');
for (let input of inputs) {
input.addEventListener('keyup', () => checkInputFields(row1Keys, row1Values)); // Row 1
input.addEventListener('keyup', () => checkInputFields(row2Keys, row2Values)); // Row 2
}
First row: <input type="text" id="row1-field1"> <input type="text" id="row1-field2">
<br>
Second row: <input type="text" id="row2-field1"> <input type="text" id="row2-field2"> <input type="text" id="row2-field3">
如果在第一行中键入hello,world,则两个输入字段均为绿色。如果在第二行中键入1、2、3,则所有3个输入字段均为绿色。您可以添加任意多的行,只需将它们保存到变量中并将它们传递给函数checkInputFields
的参数即可。