使用jQuery、XML、JSON、JS遍历表

时间:2021-08-31 14:28:28

Sorry for the misleading title but I'm unsure how else to write it.

很抱歉这个标题误导了我,但我不确定还能怎么写。

I have the below table...

我有下表……

使用jQuery、XML、JSON、JS遍历表

I want to produce a simple calculator that compares all data in a row from 2 given parameters.

我想生成一个简单的计算器,它将一行中的所有数据与两个给定参数进行比较。

I will ask my users to select a country first, and then select a value in that column. After doing this you can submit the form and it would output the correct values from that given row...

我将要求我的用户先选择一个国家,然后在该列中选择一个值。这样做之后,您可以提交表单,它将从给定的行中输出正确的值……

I've made a fiddle to try and show what I mean...

我弄了一把小提琴来试着表达我的意思……

http://jsfiddle.net/SLCaN/2/

http://jsfiddle.net/SLCaN/2/

What is the best way to do this? The only way I am aware of is by having a huge if/else statement which will take me forever to write.

最好的方法是什么?我意识到的唯一方式是有一个巨大的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');
});

If you select French and 5a+ you would get 5.8 and V-Diff in the output...

如果你选择French和5a+,你会得到5.8和V-Diff输出…

7 个解决方案

#1


1  

There are definitely different ways to do this, but it seems to me that it comes down to the data structure. My personal take is to go with a data structure that has an array of countries with grades. The grades would then actually be pairs (display value/actual value) to account for the gaps in the data. The trick here is that we don't want to display empty display values in the select, but we do need data (in actual value) for conversion. After that, the jQuery stuff is pretty easy.

当然有不同的方法可以做到这一点,但在我看来,这取决于数据结构。我个人的观点是采用一种数据结构,其中包含了一系列有分数的国家。然后,分数实际上是成对(显示值/实际值)来解释数据中的差距。这里的诀窍是,我们不希望在select中显示空的显示值,但我们确实需要数据(在实际值中)进行转换。在那之后,jQuery就变得非常简单了。

Data like this:

数据是这样的:

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"], 
        ["", ""], 
        ["", ""]
    ]}
];

Event handling, etc. like this:

事件处理等如下:

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);
});

Check out a working JSFiddle here: http://jsfiddle.net/tetonraven/SVj63/

这里有一个可用的JSFiddle: http://jsfiddle.net/tetonraven/SVj63/

#2


1  

Iserni's Answer is really close to what you need, I think they missed the output portion though unless I'm reading/understanding the code incorrectly.

Iserni的答案非常接近您所需要的,我认为他们错过了输出部分,除非我阅读/理解错误的代码。

To adapt that answer a bit I would change the data structure to be:

为了适应这个答案,我将把数据结构改为:

var grades = [
{'fr': "4", 'usa': "5.6",'gb': ""},
{'fr': "4", 'usa': "5.6",'gb': "Mod"},
{'fr': "5a",    'usa': "5.7",'gb': "Diff"},
{'fr': "5a+",   'usa': "5.7",'gb': "V-Diff"},
{'fr': "5b",    'usa': "5.8",'gb': "4a"},
{'fr': "5b+",   'usa': "5.8",'gb': "4b"},
{'fr': "5c",    'usa': "5.9",'gb': "4b VS"},
{'fr': "5c+",   'usa': "5.10a",'gb': "4c HVS"},
{'fr': "6a",    'usa': "5.10b",'gb': "5a E1"},
{'fr': "6a+",   'usa': "5.10c",'gb': ""},
{'fr': "6b",    'usa': "5.10d",'gb': ""}];

Then in your click event something like this will get you to translated values (you will need to adapt it a bit)

然后在单击事件中,类似这样的内容将使您获得转换后的值(您需要对其进行一些调整)

$('input[type="submit"]').on('click', function(e){
   e.preventDefault();
   var matches = $.grep(grades,function(e) {
     return e[$(".country").val()] == $('.iniValusa').val()
   });

   if(matches.length == 1)
   {
     $('p').text('USA: ' + matches[0].usa + ' GB: ' + matches[0].gb + 'FR: ' + matches[0].fr);
   } 
});

#3


1  

crush's solution seems to me the most practical. You define the data in a single variable, then use it to populate both SELECTs. However, consider that Michael's solution can be adapted to degrade better: my take on crush's solution, if Javascript were disabled, would get you an empty page.

对我来说,压碎的解决方案是最实用的。在单个变量中定义数据,然后使用它填充两个选择。但是,考虑到可以对Michael的解决方案进行更好的降级:我对crush的解决方案的看法是,如果禁用了Javascript,将会得到一个空页面。

You keep all the data in a Javascript object, and the values are indexed so that equal grades have equal indexes (the row numbers in your table):

您将所有数据保存在一个Javascript对象中,并对值进行索引,以便相等的等级具有相等的索引(表中的行号):

 4: "quatrième valeur pour les français",
 ...
 4: "Fourth value for UK",

This approach allows to "translate" more easily (I believe) one array into the other, i.e. you select France, get grade 5b, change France to US: the value stays the same, which means that the displayed grade changes to the corresponding value in the new country.

这种方法使“翻译”更容易(我相信)一个数组进入另一个数组,即你选择法国,得到5b级,将法国改为我们:值保持不变,这意味着在新国家中显示的等级改变对应的值。

Also, you keep all your data in a single place.

同时,您将所有数据保存在一个地方。

For large country arrays, I'd suggest to convert the grades[countryCode] into an AJAX call to fetch that particular country from the server. You'd also need another AJAX call to only fetch the codes from the server.

对于大型的国家数组,我建议将等级(countryCode)转换为AJAX调用,从服务器获取特定的国家。您还需要另一个AJAX调用来只从服务器获取代码。

  var grades = {
    fr: {
        name: 'France',
        values: {
            0: "4",
            1: "4",
            2: "5a",
            3: "5a+",
            4: "5b",
            5: "5b+",
            6: "5c",
            7: "5c+",
            8: "6a",
            9: "6a+",
           10: "6b"
        }
     },
 us:    {
        name: 'USA',
        values: {
            0: "5.6",
            1: "5.6",
            2: "5.7",
            3: "5.7",
            4: "5.8",
            5: "5.8",
            6: "5.9",
            7: "5.10a",
            8: "5.10b",
            9: "5.10c",
           10: "5.10d"
        }
    },
'gb': {
        name: 'UK',
        values: {
            0: "",
            1: "Mod",
            2: "Diff",
            3: "V-Diff",
            4: "4a",
            5: "4b",
            6: "4b VS",
            7: "4c HVS",
            8: "5a E1",
            9: "",
           10: ""
        }
  }
}


  function setSelectTo(country) {
      // TODO: verify that country is indeed in grades
      var data = grades[country].values;
      var $el = $("#gradeSelect");
      $cur = $el.val();
      $el.empty();
      $.each(data, function(value, text) {
          $el
             .append($("<option></option>")
             .attr("value", value)
             .text(text));
      });
      // Restore value
      $el.val($cur);
  }
  function populateCountrySelect() {
      var $el = $("#countrySelect");
      $el.empty();

      $.each(grades, function(code, data) {
          $el
             .append($("<option></option>")
             .attr("value", code)
             .text(data.name));
      });
  }

  $('#countrySelect').on('change', function(){
      setSelectTo($(this).val());
  });

  populateCountrySelect();
  $('#countrySelect').val('us');
  setSelectTo('us');
  $('#gradeSelect').val(2);

This is an updated sample fiddle - sorry, the first URL was wrong - and the HTML is very minimal:

这是一个更新的示例小提琴-对不起,第一个URL是错误的- HTML是非常小的:

Choose your country: <select id="countrySelect"></select>
<br />
Choose your grade: <select id="gradeSelect"></select>            

#4


0  

As per my understanding adding my 2 penny to access the data, and hope its helpful.

根据我的理解,增加我的2便士来访问数据,并希望它能有所帮助。

Keep data like every first select value and the grade value array .

保存数据,就像每个first select值和grade value数组一样。

 var data = { 
 fr :new Array("4","4","5a","5a+", "5b","5b+","5c","5c+","6a","6a+", "6b"),  

 usa : new Array(  "5.6","5.6","5.7", "5.7","5.8", "5.8", "5.9", "5.10a", "5.10b","5.10c", "5.10d"), 

 gb : new Array (  "", "Mod","Diff","V-Diff", "4a","4b", "4b VS", "4c HVS", "5a E1", "","")                            

};

Then write the method to populate that grades when country clicks.

然后编写方法,在国家单击时填充该分数。

function populate(val)
{    
      $("#grade").empty();   
    var array = data[val];   
   for(var a=0; a<array.length; a++ ) {
     $("#grade").append('<option value="'+ a +  '">' +  array[a] + '</option>');
}    
 }    
}

And call the methods something like that ::

方法是这样的:

$("document").ready(function () { populate('usa'); } );
$('.country').on('change', function(){
    populate($(this).val());  
});

Html will be simple (only country u need to per-populate [U can write the method to poulate them in document ready also]. This the output way to print all content to select index : {As per ur expected o/p my understanding is u skiping the empty value, u can add that cond here if that the case something like this : if(data[a][index] == '') data[a][index+1] (though u have to take care array len etc.) }

Html将是简单的(只有国家u需要填充[u也可以编写方法在文档中填充它们])。这个输出打印所有内容的方式来选择指数:{按照你的预期o / p u跳过我的理解是空值,你可以添加,气孔导度,如果情况是这样的:如果(数据(一个)(指数)= =”)数据[一][指数+ 1](尽管你必须照顾数组len等等)}

$('input[type="submit"]').on('click', function(e){
    e.preventDefault();
    var index = $('#grade').find(":selected").val();
     var str = "";
     for(var a in data)
     {         
        str  = str +" " + $('.country option[value="' + a + '"]').html() 
        +" " + data[a][index];
    }
    $('p').text('Values output here ' + str);
 }); 

DEMO

演示

#5


0  

Ok, I don't exactly know how you want. But I tried that with html table + jQuery and here is what you can get.

好吧,我不知道你到底想要什么。但是我在html表格+ jQuery中尝试过,这里是你能得到的。

DEMO http://jsfiddle.net/yeyene/xEzLv/

You only need 3 if statements and see the result.

只需要3个if语句就可以看到结果。

$('.country').on('change', function(){
    $('.hiddenGrade').hide();
    $('#s_'+$(this).val()).show();
    $('#cn').val($(this).val());
    $('#result').val('');
});
$('.hiddenGrade').on('change', function(){
    $('#cn_val').val($(this).val());
    $('#chart tr').css('background', 'none');
    $('#chart tr').eq($(this).val()).css('background', 'green');
});

$('input[type="submit"]').on('click', function(e){
    e.preventDefault();
    if($('#cn').val() === '0'){
        $('#result').val(
            $('#chart tr').eq($('#cn_val').val()).find('td').eq(1).text()+', '+
            $('#chart tr').eq($('#cn_val').val()).find('td').eq(2).text()   
        );
    }
    if($('#cn').val() === '1'){
        $('#result').val(
            $('#chart tr').eq($('#cn_val').val()).find('td').eq(0).text()+', '+
            $('#chart tr').eq($('#cn_val').val()).find('td').eq(2).text()   
        );
    }
    if($('#cn').val() === '2'){
        $('#result').val(
            $('#chart tr').eq($('#cn_val').val()).find('td').eq(0).text()+', '+
            $('#chart tr').eq($('#cn_val').val()).find('td').eq(1).text()   
        );
    }
});

#6


0  

I do not like enormous ammount of code other answers have. Check fiddle http://jsfiddle.net/vittore/kP249/1/.

我不喜欢大量的代码的其他答案。检查小提琴http://jsfiddle.net/vittore/kP249/1/。

Just put data in table:

<select id='country'>
    <option value="0">Fr</option>
    <option value="1">Us</option>
    <option value="2">Uk</option>
</select>
<input id='score' type="text" />    

<table id="results">
    <thead><tr><td>Fr</td><td>Us</td><td>Uk</td></tr></thead><tbody>
    <tr><td>4</td><td>5.6</td><td></td></tr>
    <tr><td>4</td><td>5.6</td><td>Mod</td></tr>
    <tr><td>5a</td><td>5.7</td><td>Diff</td></tr>
    <tr><td>5a+</td><td>5.7</td><td>V-Diff</td></tr>
    <tr><td>5b</td><td>5.8</td><td>4a</td></tr>
    <tr><td>5b+</td><td>5.8</td><td>4b</td></tr>
    <tr><td>5c</td><td>5.9</td><td>4b VS</td></tr>
    <tr><td>5c+</td><td>5.10a</td><td>4c HVS</td></tr>
    <tr><td>6a</td><td>5.10b</td><td>5a E1</td></tr>
    <tr><td>6a+</td><td>5.10c</td><td></td></tr>                   
</tbody></table>

And add little bit of javascript:

再加上一点javascript:

var $score = $('#score'), $country = $('#country')
  , $results = $('#results'), $rows = $results.find('tbody tr')

$rows.hide()

$results.on('scoreChanged', function(e, country, score) {
    $rows.hide().filter(function(i) {
        return $(this).find('td:eq(' + country + ')').text() == score
    }).show()
})

$score.on('submit, blur', function(e) {
  $results.trigger('scoreChanged', [$country.val(), $score.val()])  
})

$country.on('changed', function(e) {
  $results.trigger('scoreChanged', [$country.val(), $score.val()])  
})

NOTE: you can slightly change filter condition and show results more friendly (fiddle):

注意:你可以稍微改变过滤条件,显示更友好的结果(小提琴):

$results.on('scoreChanged', function(e, country, score) {
    $rows.hide().filter(function(i) {
        return $(this).find('td:eq(' + country + ')').text().contains(score)
    }).show()
})

#7


0  

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script type="text/javascript" src="jquery-2.1.0.min.js"></script>
    <script type="text/javascript">
        $(function(){

            var values = [['', '', ''], ['4', '5.6', 'x'], ['5a', '5.7', 'dif']];
            var countries = ['-', 'fr', 'us', 'uk'];
            var jq_country =  $('.country'), jq_grade = $('.grade');

            $.each(countries, function(index, val){
               jq_country.append('<option data-index="' + index + '">' + val + '</option>');                
            });

            var curr_col, curr_index;

            jq_country.change(function() {
                jq_grade.empty();     
                $('.result').val('');

                curr_col = parseInt($(this).find('option:selected').data('index')) - 1;     

                if (curr_col >= 0) {

                    $.each(values, function(index, val) {

                        jq_grade.append('<option ' + (index == curr_index ? 'selected' : '' ) +  ' value="' + index + '">' + val[curr_col] + '</option>')   
                    });


                    jq_grade.change();
                }

            });

            jq_grade.change(function() {
                curr_index = parseInt(jq_grade.val());
                if (curr_index) {
                    var result = '';
                    $.each(countries.slice(1), function(index, val){
                        if (index != curr_col) result += val + ':' + values[curr_index][index] + ';';
                    });

                    $('.result').val(result);
                }
                else {
                    $('.result').val('');
                }
            });            

        })
    </script>

</head>
<body>
    <form method="post">
       <select class="country"></select>
      <select class="grade"></select>
      <input type="text" class="result" />
   </form>

</body>
</html>

#1


1  

There are definitely different ways to do this, but it seems to me that it comes down to the data structure. My personal take is to go with a data structure that has an array of countries with grades. The grades would then actually be pairs (display value/actual value) to account for the gaps in the data. The trick here is that we don't want to display empty display values in the select, but we do need data (in actual value) for conversion. After that, the jQuery stuff is pretty easy.

当然有不同的方法可以做到这一点,但在我看来,这取决于数据结构。我个人的观点是采用一种数据结构,其中包含了一系列有分数的国家。然后,分数实际上是成对(显示值/实际值)来解释数据中的差距。这里的诀窍是,我们不希望在select中显示空的显示值,但我们确实需要数据(在实际值中)进行转换。在那之后,jQuery就变得非常简单了。

Data like this:

数据是这样的:

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"], 
        ["", ""], 
        ["", ""]
    ]}
];

Event handling, etc. like this:

事件处理等如下:

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);
});

Check out a working JSFiddle here: http://jsfiddle.net/tetonraven/SVj63/

这里有一个可用的JSFiddle: http://jsfiddle.net/tetonraven/SVj63/

#2


1  

Iserni's Answer is really close to what you need, I think they missed the output portion though unless I'm reading/understanding the code incorrectly.

Iserni的答案非常接近您所需要的,我认为他们错过了输出部分,除非我阅读/理解错误的代码。

To adapt that answer a bit I would change the data structure to be:

为了适应这个答案,我将把数据结构改为:

var grades = [
{'fr': "4", 'usa': "5.6",'gb': ""},
{'fr': "4", 'usa': "5.6",'gb': "Mod"},
{'fr': "5a",    'usa': "5.7",'gb': "Diff"},
{'fr': "5a+",   'usa': "5.7",'gb': "V-Diff"},
{'fr': "5b",    'usa': "5.8",'gb': "4a"},
{'fr': "5b+",   'usa': "5.8",'gb': "4b"},
{'fr': "5c",    'usa': "5.9",'gb': "4b VS"},
{'fr': "5c+",   'usa': "5.10a",'gb': "4c HVS"},
{'fr': "6a",    'usa': "5.10b",'gb': "5a E1"},
{'fr': "6a+",   'usa': "5.10c",'gb': ""},
{'fr': "6b",    'usa': "5.10d",'gb': ""}];

Then in your click event something like this will get you to translated values (you will need to adapt it a bit)

然后在单击事件中,类似这样的内容将使您获得转换后的值(您需要对其进行一些调整)

$('input[type="submit"]').on('click', function(e){
   e.preventDefault();
   var matches = $.grep(grades,function(e) {
     return e[$(".country").val()] == $('.iniValusa').val()
   });

   if(matches.length == 1)
   {
     $('p').text('USA: ' + matches[0].usa + ' GB: ' + matches[0].gb + 'FR: ' + matches[0].fr);
   } 
});

#3


1  

crush's solution seems to me the most practical. You define the data in a single variable, then use it to populate both SELECTs. However, consider that Michael's solution can be adapted to degrade better: my take on crush's solution, if Javascript were disabled, would get you an empty page.

对我来说,压碎的解决方案是最实用的。在单个变量中定义数据,然后使用它填充两个选择。但是,考虑到可以对Michael的解决方案进行更好的降级:我对crush的解决方案的看法是,如果禁用了Javascript,将会得到一个空页面。

You keep all the data in a Javascript object, and the values are indexed so that equal grades have equal indexes (the row numbers in your table):

您将所有数据保存在一个Javascript对象中,并对值进行索引,以便相等的等级具有相等的索引(表中的行号):

 4: "quatrième valeur pour les français",
 ...
 4: "Fourth value for UK",

This approach allows to "translate" more easily (I believe) one array into the other, i.e. you select France, get grade 5b, change France to US: the value stays the same, which means that the displayed grade changes to the corresponding value in the new country.

这种方法使“翻译”更容易(我相信)一个数组进入另一个数组,即你选择法国,得到5b级,将法国改为我们:值保持不变,这意味着在新国家中显示的等级改变对应的值。

Also, you keep all your data in a single place.

同时,您将所有数据保存在一个地方。

For large country arrays, I'd suggest to convert the grades[countryCode] into an AJAX call to fetch that particular country from the server. You'd also need another AJAX call to only fetch the codes from the server.

对于大型的国家数组,我建议将等级(countryCode)转换为AJAX调用,从服务器获取特定的国家。您还需要另一个AJAX调用来只从服务器获取代码。

  var grades = {
    fr: {
        name: 'France',
        values: {
            0: "4",
            1: "4",
            2: "5a",
            3: "5a+",
            4: "5b",
            5: "5b+",
            6: "5c",
            7: "5c+",
            8: "6a",
            9: "6a+",
           10: "6b"
        }
     },
 us:    {
        name: 'USA',
        values: {
            0: "5.6",
            1: "5.6",
            2: "5.7",
            3: "5.7",
            4: "5.8",
            5: "5.8",
            6: "5.9",
            7: "5.10a",
            8: "5.10b",
            9: "5.10c",
           10: "5.10d"
        }
    },
'gb': {
        name: 'UK',
        values: {
            0: "",
            1: "Mod",
            2: "Diff",
            3: "V-Diff",
            4: "4a",
            5: "4b",
            6: "4b VS",
            7: "4c HVS",
            8: "5a E1",
            9: "",
           10: ""
        }
  }
}


  function setSelectTo(country) {
      // TODO: verify that country is indeed in grades
      var data = grades[country].values;
      var $el = $("#gradeSelect");
      $cur = $el.val();
      $el.empty();
      $.each(data, function(value, text) {
          $el
             .append($("<option></option>")
             .attr("value", value)
             .text(text));
      });
      // Restore value
      $el.val($cur);
  }
  function populateCountrySelect() {
      var $el = $("#countrySelect");
      $el.empty();

      $.each(grades, function(code, data) {
          $el
             .append($("<option></option>")
             .attr("value", code)
             .text(data.name));
      });
  }

  $('#countrySelect').on('change', function(){
      setSelectTo($(this).val());
  });

  populateCountrySelect();
  $('#countrySelect').val('us');
  setSelectTo('us');
  $('#gradeSelect').val(2);

This is an updated sample fiddle - sorry, the first URL was wrong - and the HTML is very minimal:

这是一个更新的示例小提琴-对不起,第一个URL是错误的- HTML是非常小的:

Choose your country: <select id="countrySelect"></select>
<br />
Choose your grade: <select id="gradeSelect"></select>            

#4


0  

As per my understanding adding my 2 penny to access the data, and hope its helpful.

根据我的理解,增加我的2便士来访问数据,并希望它能有所帮助。

Keep data like every first select value and the grade value array .

保存数据,就像每个first select值和grade value数组一样。

 var data = { 
 fr :new Array("4","4","5a","5a+", "5b","5b+","5c","5c+","6a","6a+", "6b"),  

 usa : new Array(  "5.6","5.6","5.7", "5.7","5.8", "5.8", "5.9", "5.10a", "5.10b","5.10c", "5.10d"), 

 gb : new Array (  "", "Mod","Diff","V-Diff", "4a","4b", "4b VS", "4c HVS", "5a E1", "","")                            

};

Then write the method to populate that grades when country clicks.

然后编写方法,在国家单击时填充该分数。

function populate(val)
{    
      $("#grade").empty();   
    var array = data[val];   
   for(var a=0; a<array.length; a++ ) {
     $("#grade").append('<option value="'+ a +  '">' +  array[a] + '</option>');
}    
 }    
}

And call the methods something like that ::

方法是这样的:

$("document").ready(function () { populate('usa'); } );
$('.country').on('change', function(){
    populate($(this).val());  
});

Html will be simple (only country u need to per-populate [U can write the method to poulate them in document ready also]. This the output way to print all content to select index : {As per ur expected o/p my understanding is u skiping the empty value, u can add that cond here if that the case something like this : if(data[a][index] == '') data[a][index+1] (though u have to take care array len etc.) }

Html将是简单的(只有国家u需要填充[u也可以编写方法在文档中填充它们])。这个输出打印所有内容的方式来选择指数:{按照你的预期o / p u跳过我的理解是空值,你可以添加,气孔导度,如果情况是这样的:如果(数据(一个)(指数)= =”)数据[一][指数+ 1](尽管你必须照顾数组len等等)}

$('input[type="submit"]').on('click', function(e){
    e.preventDefault();
    var index = $('#grade').find(":selected").val();
     var str = "";
     for(var a in data)
     {         
        str  = str +" " + $('.country option[value="' + a + '"]').html() 
        +" " + data[a][index];
    }
    $('p').text('Values output here ' + str);
 }); 

DEMO

演示

#5


0  

Ok, I don't exactly know how you want. But I tried that with html table + jQuery and here is what you can get.

好吧,我不知道你到底想要什么。但是我在html表格+ jQuery中尝试过,这里是你能得到的。

DEMO http://jsfiddle.net/yeyene/xEzLv/

You only need 3 if statements and see the result.

只需要3个if语句就可以看到结果。

$('.country').on('change', function(){
    $('.hiddenGrade').hide();
    $('#s_'+$(this).val()).show();
    $('#cn').val($(this).val());
    $('#result').val('');
});
$('.hiddenGrade').on('change', function(){
    $('#cn_val').val($(this).val());
    $('#chart tr').css('background', 'none');
    $('#chart tr').eq($(this).val()).css('background', 'green');
});

$('input[type="submit"]').on('click', function(e){
    e.preventDefault();
    if($('#cn').val() === '0'){
        $('#result').val(
            $('#chart tr').eq($('#cn_val').val()).find('td').eq(1).text()+', '+
            $('#chart tr').eq($('#cn_val').val()).find('td').eq(2).text()   
        );
    }
    if($('#cn').val() === '1'){
        $('#result').val(
            $('#chart tr').eq($('#cn_val').val()).find('td').eq(0).text()+', '+
            $('#chart tr').eq($('#cn_val').val()).find('td').eq(2).text()   
        );
    }
    if($('#cn').val() === '2'){
        $('#result').val(
            $('#chart tr').eq($('#cn_val').val()).find('td').eq(0).text()+', '+
            $('#chart tr').eq($('#cn_val').val()).find('td').eq(1).text()   
        );
    }
});

#6


0  

I do not like enormous ammount of code other answers have. Check fiddle http://jsfiddle.net/vittore/kP249/1/.

我不喜欢大量的代码的其他答案。检查小提琴http://jsfiddle.net/vittore/kP249/1/。

Just put data in table:

<select id='country'>
    <option value="0">Fr</option>
    <option value="1">Us</option>
    <option value="2">Uk</option>
</select>
<input id='score' type="text" />    

<table id="results">
    <thead><tr><td>Fr</td><td>Us</td><td>Uk</td></tr></thead><tbody>
    <tr><td>4</td><td>5.6</td><td></td></tr>
    <tr><td>4</td><td>5.6</td><td>Mod</td></tr>
    <tr><td>5a</td><td>5.7</td><td>Diff</td></tr>
    <tr><td>5a+</td><td>5.7</td><td>V-Diff</td></tr>
    <tr><td>5b</td><td>5.8</td><td>4a</td></tr>
    <tr><td>5b+</td><td>5.8</td><td>4b</td></tr>
    <tr><td>5c</td><td>5.9</td><td>4b VS</td></tr>
    <tr><td>5c+</td><td>5.10a</td><td>4c HVS</td></tr>
    <tr><td>6a</td><td>5.10b</td><td>5a E1</td></tr>
    <tr><td>6a+</td><td>5.10c</td><td></td></tr>                   
</tbody></table>

And add little bit of javascript:

再加上一点javascript:

var $score = $('#score'), $country = $('#country')
  , $results = $('#results'), $rows = $results.find('tbody tr')

$rows.hide()

$results.on('scoreChanged', function(e, country, score) {
    $rows.hide().filter(function(i) {
        return $(this).find('td:eq(' + country + ')').text() == score
    }).show()
})

$score.on('submit, blur', function(e) {
  $results.trigger('scoreChanged', [$country.val(), $score.val()])  
})

$country.on('changed', function(e) {
  $results.trigger('scoreChanged', [$country.val(), $score.val()])  
})

NOTE: you can slightly change filter condition and show results more friendly (fiddle):

注意:你可以稍微改变过滤条件,显示更友好的结果(小提琴):

$results.on('scoreChanged', function(e, country, score) {
    $rows.hide().filter(function(i) {
        return $(this).find('td:eq(' + country + ')').text().contains(score)
    }).show()
})

#7


0  

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script type="text/javascript" src="jquery-2.1.0.min.js"></script>
    <script type="text/javascript">
        $(function(){

            var values = [['', '', ''], ['4', '5.6', 'x'], ['5a', '5.7', 'dif']];
            var countries = ['-', 'fr', 'us', 'uk'];
            var jq_country =  $('.country'), jq_grade = $('.grade');

            $.each(countries, function(index, val){
               jq_country.append('<option data-index="' + index + '">' + val + '</option>');                
            });

            var curr_col, curr_index;

            jq_country.change(function() {
                jq_grade.empty();     
                $('.result').val('');

                curr_col = parseInt($(this).find('option:selected').data('index')) - 1;     

                if (curr_col >= 0) {

                    $.each(values, function(index, val) {

                        jq_grade.append('<option ' + (index == curr_index ? 'selected' : '' ) +  ' value="' + index + '">' + val[curr_col] + '</option>')   
                    });


                    jq_grade.change();
                }

            });

            jq_grade.change(function() {
                curr_index = parseInt(jq_grade.val());
                if (curr_index) {
                    var result = '';
                    $.each(countries.slice(1), function(index, val){
                        if (index != curr_col) result += val + ':' + values[curr_index][index] + ';';
                    });

                    $('.result').val(result);
                }
                else {
                    $('.result').val('');
                }
            });            

        })
    </script>

</head>
<body>
    <form method="post">
       <select class="country"></select>
      <select class="grade"></select>
      <input type="text" class="result" />
   </form>

</body>
</html>