【问题标题】:Display table row based on the selected option of Select html tag根据 Select html 标签的选中选项显示表格行
【发布时间】:2015-04-13 19:05:44
【问题描述】:

所以我尝试根据用户所在的国家/地区显示表格的内容。基本上,如果用户选择美国作为选项,他会得到一个包含显示美国数据的表格行。我使用带有选项的选择,每个选项都有国家的域扩展作为值(例如,对于巴西选项,值为 br :<option value="br">Brazil</option>,加上它的表行与 ID 具有相同的选项值 (<tr id="br" style="display: none;">..</tr>)

用户在选项中选择国家/地区后,是否有任何脚本可以显示国家/地区数据?

谢谢,这是我的代码:

HTML:

<select id="data">
  <option value="#">Select a country ..</option>
  <option value="us">United States</option>
  <option value="es">Spain</option>
 <!-- more countries -->
</select>


<div id="container">

<table border="1">
 <tr>
  <td> Country </td>
  <td> Chance</td>
 </tr>
 <tr id="us"  style="display: none;">
  <td> United States </td>
  <td> 2.02 % </td>
 </tr>
 <tr id="es" style="display: none;">
  <td> Spain </td>
  <td> 2.12 % </td>
 </tr>
</table>

</div>

我尝试了以下方法:

Jquery:

$('#data').change(function() {
    $('tr#($(this).val())').css('display','block');
});

问候,

谢谢!

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:

    这不是连接的方式,试试这个:

    $('#data').change(function() {
        $('tr#' + $(this).val()).css('display','block');
    });
    

    使用 OP 注释编辑:

    为所有应该隐藏/显示的 TR 添加一个类,然后:

    <table border="1">
     <tr>
      <td> Country </td>
      <td> Chance</td>
     </tr>
     <tr class="hideShowTr" id="us"  style="display: none;">
      <td> United States </td>
      <td> 2.02 % </td>
     </tr>
     <tr class="hideShowTr" id="es" style="display: none;">
      <td> Spain </td>
      <td> 2.12 % </td>
     </tr>
    </table>
    
    $('#data').change(function() {
        $('.hideShowTr').css('display','none');
        $('tr#' + $(this).val()).css('display','block');
    });
    

    【讨论】:

    • 非常感谢你,这是有效的。我仍然有一个问题,使用您的代码我可以看到我已经选择的所有国家/地区,一旦未选择该选项,是否有一些代码可以删除 display: block ?我认为您需要添加一些else 代码.. 对不起我的英语和作为 JS 新手。尽可能接受答案。
    • 确实做到了,非常感谢!!
    • 没问题,很高兴能帮到你:)
    【解决方案2】:

    试试这个:

    $('#data').change(function() {
    //Only show specific row    
    $('tr#' + $(this).val()).show();
    //hide other rows
    $("tr:not(:#"+$(this).val()+")").hide(); 
    });
    

    【讨论】:

    • 我认为这里面多了一个冒号。这对我有用,但只有在我将 $("tr:not(:#" 更改为 $("tr:not(#"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多