javascript - 使用 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');
})
照片:
解决方案
你不能给<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');
})
推荐阅读
- java - 如何在 Java 中访问 AWS Lambda 回调结果
- javascript - 如果那里有对象,请更改功能
- python - ROS 中是否需要 C++ 和 Python
- mysql - 跟踪当前商店中的物品以及在任何给定月份的商店中的物品
- angularjs - Typescript - 如何为 json 对象创建嵌套接口
- javascript - 预检响应中的 Access-Control-Allow-Methods 不允许方法 PATCH
- php - PHP:在表单提交中获取复选框值和文本字段值
- javascript - javascript 整数数组中可用于获取总值的最少元素
- php - 谷歌浏览器扩展 GMAIL 生成带参数的 URL
- java - java.lang.IllegalArgumentException:在 okhttp3.Headers$Builder.checkNameAndValue