隐藏/显示的最佳方法取决于jQuery的选择选项

Best way to hide/show depending on select options with jQuery?

本文关键字:jQuery 选择 选项 取决于 最佳 显示 隐藏 方法      更新时间:2023-09-26

我有一个选择,里面有两个选项。我希望默认选项在选择元素下方显示输入,而另一个选项在选择时隐藏该输入,而是显示一段文本。我尝试使用绑定和更改,但我无法让它工作。最好的方法是什么?

这是一个微小的、可重用的函数,可以减少显示/隐藏的一些代码混乱。

jQuery.fn.showIf = function (condition) {
return this[condition ? 'show' : 'hide']();
}

你像这样使用它:

$('#foo').change(function() {
    $('#input').showIf(el.val() === "1");
    $('#text').showIf(el.val() !== "1");
});

沿着这些思路的东西应该可以解决问题:

​<select id="foo">
    <option value="1">Enter a value</option>
    <option value="2">Show some text</option>
</select>
<input id="input" type="text"/>
<p id="text" style="display:none">
    Blah blah blah blah blah blah blah blah 
    blah blah blah blah blah blah blah blah 
</p>​​​​​​​​​​​

​$('#foo').change(function() {
    var el = $(this);
    if(el.val() === "1") {
        $('#input').show();
        $('#text').hide();            
    } else {
        $('#text').show();
        $('#input').hide();
    }      
});​​​​​​

http://jsfiddle.net/J5Enp/