首页 > 解决方案 > 使用 jquery 选择选项标签

问题描述

我有一个下拉表单,当我选择一个选项时,应该显示带有这些标签的照片。当我将选项标签制作成 div 或 ul/li 元素时,此代码可以正常工作。虽然我知道该功能适用​​于那些,但当我将它们作为选择/选项元素时它将不起作用。

我认为问题存在于点击功能中,但无法解决。其他用于表单的 jquery 函数也没有提供解决方案。

任何帮助表示赞赏。

HTML/PHP

<form>
  <select id="industry_area">Industry:

    <option class="active industry" id="all">All</option>
        <?php
        // check if the repeater field has rows of data

                // loop through the rows of data
            while ( have_rows( 'industry_menu' ) ) :
                the_row();

                // display a sub field value
                        $industry_menu = get_sub_field( 'industry_field_name' );
                        $count = get_row_index();
                        echo "<option class='industry' id=$industry_menu> $industry_menu </option>";

                    endwhile;

        ?>

  </select>
</form>


<div id="parent">
    <?php
    foreach ( $partners as $partner ) {
        $id      = $partner->ID;
        $image   = get_the_post_thumbnail($id);
        $vip = get_field('vip', $id);
        $industry_type = get_field('industry', $id);
        $industry_type_string = $industry_type[0];
        echo
        "<div class='item $vip $industry_type_string'>
            $image
        </div>";
    }
    ?>
</div>


JS

  var $industry = $('.industry').click(function() {
    if (this.id == 'all') {
      $('#parent > div').fadeIn(450);
    } else {
      var $el = $('.' + this.id).fadeIn(450);
      $('#parent > div').not($el).hide();
    }
    $industry.removeClass('active');
    $(this).addClass('active');
    })

照片: 截图

标签: javascriptphpjquery

解决方案


你不能给<option>标签一个id属性。他们没有。

而是给<select>标签一个 id,就像你<select id="industry_area">没有在标签上设置索引属性<option>一样,你将不得不使用这样的 jquery 代码来获取选定的文本

$( "#industry_area option:selected" ).text();

你修改了代码

var $industry = $('.industry_area ').click(function() {
    if ($( "#industry_area option:selected" ).text() == 'all') {
        $('#parent > div').fadeIn(450);
    } else {
        var $el = $('.' + this.id).fadeIn(450);
        $('#parent > div').not($el).hide();
    }
    $( "#industry_area option:selected" )
        .removeClass('active')
        .addClass('active');
})

推荐阅读