Javascript 数组中的单词无明显原因地重复
我终于成功地去掉了空字符串(非常感谢Mark),但是我正忙于检查,我发现它无缘无故地复制了数组中的单词。看看我的JSON,然后看看屏幕截图 JSON:Javascript 数组中的单词无明显原因地重复,javascript,jquery,json,Javascript,Jquery,Json,我终于成功地去掉了空字符串(非常感谢Mark),但是我正忙于检查,我发现它无缘无故地复制了数组中的单词。看看我的JSON,然后看看屏幕截图 JSON: { "main_object": { "id": "new", "getExerciseTitle": "Let's go", "language": "nl_NL", "application": "lettergrepen", "main_object": { "title": "Let's go", "language": "nl_
{
"main_object": {
"id": "new",
"getExerciseTitle": "Let's go",
"language": "nl_NL",
"application": "lettergrepen",
"main_object": {
"title": "Let's go",
"language": "nl_NL",
"exercises": [
{
"word": "huisartsenpraktijk",
"syllables": [
"huis",
"artsen",
"praktijk"
]
},
{
"word": "Terschelling",
"syllables": [
"ter",
"schelling"
]
},
{
"word": "voetbalclub",
"syllables": [
"voet",
"bal",
"club"
]
}
]
},
"dataType": "json"
}
}
现在看一下屏幕截图:
注意我的数组中的单词有时是如何重复的,因此留下了空的输入字段
以下是我创建检查的方式,以查看长度是否等于JSON长度:
if (exercise.syllables.length === correctSylls.length) {
$(this).closest('.syll-row').find('input.syl-input').addClass('btn btn-success').removeClass('form-control').prop('disabled', true);
}
这就是完整函数的样子(我去掉了不相关的部分,只保留了相关的部分)
var correctSylls=[];
$.map(练习.音节,函数(音节,j){
变量sylInput=$(''{
“类型”:“文本”,
“类”:“窗体控件syl输入”,
“名称”:+c++,
“id”:+idsyll++
}).on('keyup',function(){
var cValue=$(this.val();
如果(cValue==音节){
校正推力(cValue);
控制台日志(correctSylls);
}
if(exercise.syllels.length==correctsyls.length){
$(this).closest('.syll行').find('input.syl input').addClass('btn btn success').removeClass('form-control').prop('disabled',true);
}
});
});
idsyll=0;
});
}
每次击键时都会触发keyup
事件。如果这是您想要的,您可能应该检查数组中是否已经存在该元素,并将其推送到其他位置。另一种选择是使用change
事件,该事件只会触发一次,或者使用blur
事件,该事件会在输入失去焦点时触发。但这并不能解释我的文字重复的原因,或者这是原因吗?快速编辑:然后是否可以使用模糊,但当插入正确的单词使其失去焦点时?是的。如果您将多个击键与同一个单词匹配,这可能就是原因。从你提供的小片段我看不出来。试过模糊,现在可以了。(它不复制任何单词)。所以我为你竖起大拇指,非常感谢你
var correctSylls = [];
$.map(exercise.syllables, function (syllable, j) {
var sylInput = $('<input/>', {
'type': 'text',
'class': 'form-control syl-input',
'name': +c++,
'id': +idsyll++
}).on('keyup', function() {
var cValue = $(this).val();
if (cValue === syllable) {
correctSylls.push(cValue);
console.log(correctSylls);
}
if (exercise.syllables.length === correctSylls.length) {
$(this).closest('.syll-row').find('input.syl-input').addClass('btn btn-success').removeClass('form-control').prop('disabled', true);
}
});
});
idsyll = 0;
});
}