当数组正确时,它应该将输入字段转换为 btn btn-success
按钮(有效)。现在是我似乎无法克服的部分:它们不会将其值插入到输入字段中。示例:您在输入字段中插入单词“hello”(我们假设单词“hello”是正确的),然后它会变成一个绿色按钮。然而它并没有保持它的值(value)。如何通过多个输入字段实现此目的?
代码如下所示:
}).on('blur', function() {
var cValue = $(this).val();
if(cValue === "") {
return;
}
if (cValue === syllable) {
correctSylls.push(cValue);
console.log(correctSylls);
}
if (exercise.syllables.length === correctSylls.length) {
$(this).closest('.syll-row').find('input.syl-input').replaceWith(getCorrectBtn());
S.addRight();
S.playRight();
}
我尝试附加到按钮cValue
,但这不起作用(如预期)。
创建成功按钮的函数:
function getCorrectBtn() {
var correctBtn = $('<button/>', {
'class': 'btn btn-success buttonCorrect',
'type': 'button',
'id': "button" + CBC++
});
return correctBtn;
}
这是完整的循环(以及如何创建输入字段):
$.map(exercise.syllables, function (syllable, j) {
if (!syllable || !syllable.trim().length) {
// If it doesn't exist or is an empty string, return early without creating/appending elements
return;
}
var innerSylCol = $('<div/>', {
class: 'col-md-3 inputSyllables'
});
var sylInput = $('<input/>', {
'type': 'text',
'class': 'form-control syl-input',
'name': +c++,
'id': +idsyll++
}).on('blur', function() {
var cValue = $(this).val();
if(cValue === "") {
return;
}
if (cValue === syllable) {
correctSylls.push(cValue);
console.log(correctSylls);
}
if (exercise.syllables.length === correctSylls.length) {
$(this).closest('.syll-row').find('input.syl-input').replaceWith(getCorrectBtn());
S.addRight();
S.playRight();
}
最佳答案
$(this).closest('.syll-row').find('input.syl-input').replaceWith(getCorrectBtn(cValue));
function getCorrectBtn(value) {
var correctBtn = $('<button/>', {
'class': 'btn btn-success buttonCorrect',
'type': 'button',
'id': "button" + CBC++,
'value': value
});
return correctBtn;
}
这可能应该有效。
了解 replaceWith
的工作原理。您不是简单地改变现有的输入,而是替换它。由于该值是输入的数据,因此当您替换它时,您将清除数据。因此,您必须将数据传递到 getCorrectBtn
函数并将其分配给新按钮。
关于javascript - 如何在将输入更改为按钮的同时保留所有所需的输入值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51254739/