使用jquery在wordpress中隐藏带有选项框值的表行

Hide table row with value of option box in wordpress with jquery

本文关键字:选项 jquery wordpress 隐藏 使用      更新时间:2023-09-26

我有一个表格,表格行中有一个输入字段和一个选项框,我希望只有当选择选项框中的特定值时,带有输入字段的<tr>才会出现。到目前为止,我有以下编码,它用输入字段隐藏了我的<tr>,但再也不会显示它。

 $script = <<< EOF
<script type='text/javascript'>
    jQuery(document).ready(function($) {
        $('#row_sports').hide(); //works

         if($('#sel_rugby').is(':selected') || $('#sel_climbing').is(':selected')){
             $('#row_sports').show();
         }else{
            $('#row_sports').hide();
         }
    });
</script>
EOF;
        echo $script;

    echo '<table border="1">';
    echo '  <tr>';
    echo '      <td>';
    echo '          <select name="sports">';
    echo '              <option>Baseball</option>';
    echo '              <option id="sel_rugby">Rugby</option>';
    echo '              <option>Soccer</option>';
    echo '              <option>Sailing</option>';
    echo '              <option id="sel_climbing">Climbing</option>';
    echo '          </select>';
    echo '      </td>';
    echo '  </tr>';
    echo '  <tr id="row_sports">';
    echo '      <td>';
    echo '          <input name="sports_cl_rg" />';
    echo '      </td>';
    echo '  </tr>';
    echo '</table>';

BR & THX,米贝克斯

<script type='text/javascript'>
    jQuery(document).ready(function($) {
        $('#row_sports').hide(); //works
        $('select').change(function() {
         if($('#sel_rugby').is(':selected') || $('#sel_climbing').is(':selected')){
             $('#row_sports').show();
         }else{
            $('#row_sports').hide();
         }
        });
    });
</script>

也使用更改功能.. 在这里它工作

试试这段代码:

<script type="text/javascript" charset="utf-8">
    jQuery(document).ready(function($) {
        $('#row_sports').hide(); //works
        $('select[name="sports"]').change(function() {
            var trig = ["Rugby", "Climbing"]; // set elements here
            if (trig.indexOf($(this).val()) > -1) {
                $('#row_sports').show();    
            } else {
                $('#row_sports').hide();
            }
        });
    });
    </script>

如果您在所有选项中输入 id 或通过文本而不是 id 比较它们会更好,这会更好。我的意思是使用攀登而不是sel_climbing。还要提供 id 以选择访问它,因为页面上可能有很多选择。我将其更改为按照您的代码工作,但如果您愿意,可以遵循我的建议。演示可在此处获得 JsFiddle

 $('select').change(function() {
 alert($('#sports option:selected').text());
    $('#row_sports').hide(); //works
   if($('#sports option:selected').attr('id') == "sel_rugby" || $('#sports option:selected').attr('id') == "sel_climbing"){
     $('#row_sports').show();
 }else{
    $('#row_sports').hide();
 }
});​