gpt4 book ai didi

javascript - 下拉菜单的 Onchange jQuery 事件

转载 作者:行者123 更新时间:2023-11-28 17:16:10 26 4
gpt4 key购买 nike

我有一个包含 3 个选择器的下拉菜单。我想在更改时显示每个选择器的内容。有人可以帮忙吗?

代码:https://www.codeply.com/go/M5JCiCq2qo

function myFunction() {
var x = document.getElementById("filter-extras").value;
document.getElementById("extra-filter").innerHTML = "You selected: " +
x;
}
<label class="col-md-12 pl-0">Select Type</label>
<select class="form-control custom-select mb-3 col-md-4" onchange="myFunction()" id="filter-extras">
<option selected="selected" value="fuel">Fuel replacement</option>
<option value="wifi">Portable WiFi hotspot</option>
<option value="cleaning">Post-trip cleaning</option>
</select>

<div>Content for Fuel replacement</div>
<div>Content for Portable WiFi hotspot</div>
<div>Content for Post-trip cleaning</div>

我认为使用 jQuery 会更容易做到。

最佳答案

使用普通 JS 仍然可以轻松完成此操作。您只需将 change 事件处理程序添加到 select 中,然后就可以使用选择的 value 来选择要显示和隐藏所有内容其他的,类似这样:

var content = document.querySelectorAll('.content');

document.querySelector('#filter-extras').addEventListener('change', function() {
content.forEach(function(el) { el.style.display = 'none'; });
document.querySelector('#' + this.value).style.display = 'block';
});
.content { 
display: none;
}
<label class="col-md-12 pl-0">Select Type</label>
<select class="form-control custom-select mb-3 col-md-4" id="filter-extras">
<option selected="selected" value="fuel">Fuel replacement</option>
<option value="wifi">Portable WiFi hotspot</option>
<option value="cleaning">Post-trip cleaning</option>
</select>

<div class="content" id="fuel">Content for Fuel replacement</div>
<div class="content" id="wifi">Content for Portable WiFi hotspot</div>
<div class="content" id="cleaning">Content for Post-trip cleaning</div>

如果您确实想在 jQuery 中执行此操作,这里是翻译后的相同逻辑:

var $content = $('.content');

$('#filter-extras').on('change', function() {
$content.hide();
$('#' + this.value).show();
});
.content { 
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="col-md-12 pl-0">Select Type</label>
<select class="form-control custom-select mb-3 col-md-4" id="filter-extras">
<option selected="selected" value="fuel">Fuel replacement</option>
<option value="wifi">Portable WiFi hotspot</option>
<option value="cleaning">Post-trip cleaning</option>
</select>

<div class="content" id="fuel">Content for Fuel replacement</div>
<div class="content" id="wifi">Content for Portable WiFi hotspot</div>
<div class="content" id="cleaning">Content for Post-trip cleaning</div>

关于javascript - 下拉菜单的 Onchange jQuery 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53450570/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com