抱歉标题误导了我,但我不确定该怎么写。
我有下表...
我想制作一个简单的计算器,用于比较来自 2 个给定参数的一行中的所有数据。
我会要求我的用户先选择一个国家,然后在该列中选择一个值。完成此操作后,您可以提交表单,它会从给定行输出正确的值...
我做了一个 fiddle 来尝试展示我的意思......
最好的方法是什么?我知道的唯一方法是写一个巨大的 if/else 语句,这将让我永远写不完。
$('.country').on('change', function(){
// If USA show corrent dropdown
if( $(this).val() == 'usa'){
$('.hiddenGrade').hide();
$('.iniValusa').show();
} else if( $(this).val() == 'gb'){
$('.hiddenGrade').hide();
$('.iniValgb').show();
} else {
$('.hiddenGrade').hide();
$('.iniValfr').show();
}
});
$('input[type="submit"]').on('click', function(e){
e.preventDefault();
$('p').text('Values output here');
});
如果您选择 French
和 5a+
,您将在输出中获得 5.8 和 V-Diff
...
最佳答案
肯定有不同的方法可以做到这一点,但在我看来,它归结为数据结构。我个人的看法是使用一个数据结构,该结构包含一系列带有等级的国家/地区。然后,成绩实际上是成对的(显示值/实际值)以说明数据中的差距。这里的技巧是我们不想在选择中显示空的显示值,但我们确实需要数据(实际值)进行转换。之后,jQuery 的东西就很简单了。
这样的数据:
var countryGrades = [
{ country : "France", grades : [
["4", "4"],
["", "4"],
["5a", "5a"],
["5a+", "5a+"],
["5b", "5b"],
["5b+", "5b+"],
["5c", "5c"],
["5c+", "5c+"],
["6a", "6a"],
["6a+", "6a+"],
["6b", "6b"]
]},
{ country : "USA", grades : [
["5.6", "5.6"],
["", "5.6"],
["5.7", "5.7"],
["", "5.7"],
["5.8", "5.8"],
["", "5.8"],
["5.9", "5.9"],
["5.10a", "5.10a"],
["5.10b", "5.10b"],
["5.10c", "5.10c"],
["5.10d", "5.10d"]
]},
{ country : "UK", grades : [
["", ""],
["Mod", "Mod"],
["Diff", "Diff"],
["V-Diff", "V-Diff"],
["4a", "4a"],
["4b", "4b"],
["4b VS", "4b VS"],
["4c HVS", "4c HVS"],
["5a E1", "5a E1"],
["", ""],
["", ""]
]}
];
事件处理等类似这样:
function loadGrades(countryGradesIndex) {
var gradeSelect = $("#grade");
gradeSelect.empty();
$.each(countryGrades[countryGradesIndex].grades, function(index, grade) {
if (grade[0] != "") {
gradeSelect.append($("<option></option>").attr("value", index).text(grade[0]));
}
});
}
$.each(countryGrades, function(index, countryGrade) {
$("#country").append($("<option></option>").attr("value", index).text(countryGrade.country));
});
$("#country").on("change", function() {
loadGrades($("#country").val());
});
loadGrades(0);
$("#convert").on("click", function() {
var gradeIndex = $("#grade").val();
var gradeConversion = "";
$.each(countryGrades, function(countryGradesIndex) {
gradeConversion += countryGrades[countryGradesIndex].country + ": " + countryGrades[countryGradesIndex].grades[gradeIndex][1] + "<br>";
});
$("#conversions").html(gradeConversion);
});
在这里查看一个有效的 JSFiddle:http://jsfiddle.net/tetonraven/SVj63/
关于javascript - 使用 jQuery、XML、JSON、JS 遍历表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21839145/