如何使用 jQuery 根据所选选项显示和隐藏元素?
这是我的代码。为什么它不起作用?
<Script>
$('#colorselector').change(function() {
$('.colors').hide();
$('#' + $(this).val()).show();
});
</Script>
<Select id="colorselector">
<option value="red">Red</option>
<option value="yellow">Yellow</option>
<option value="blue">Blue</option>
</Select>
<div id="red" class="colors" style="display:none"> .... </div>
<div id="yellow" class="colors" style="display:none"> ... </div>
<div id="blue" class="colors" style="display:none"> ... </div>
Here is my code. Why it doesn't work?
<Script>
$('#colorselector').change(function() {
$('.colors').hide();
$('#' + $(this).val()).show();
});
</Script>
<Select id="colorselector">
<option value="red">Red</option>
<option value="yellow">Yellow</option>
<option value="blue">Blue</option>
</Select>
<div id="red" class="colors" style="display:none"> .... </div>
<div id="yellow" class="colors" style="display:none"> ... </div>
<div id="blue" class="colors" style="display:none"> ... </div>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您在加载 DOM 之前运行代码。
试试这个:
实例:
http://jsfiddle.net/FvMYz/
You're running the code before the DOM is loaded.
Try this:
Live example:
http://jsfiddle.net/FvMYz/
对每个值都这样做
Do like this for every value
要在选择一个值时显示 div,并在从下拉框中选择另一个值时隐藏:-
To show the div while selecting one value and hide while selecting another value from dropdown box: -
您在
show()
的选择器上缺少:selected
- 请参阅 jQuery 文档 了解如何使用它的示例。在你的情况下,它可能看起来像这样:
You are missing a
:selected
on the selector forshow()
- see the jQuery documentation for an example of how to use this.In your case it will probably look something like this: