jquery show hide div基于选择值

Duš*_*šan 12 javascript jquery

我有一个选择列表,其中包括"全部"和"自定义".在选择值为'custom'时,应显示带有"资源"类的div,如果值为"all"则应隐藏.

表格是:

<div>
    <label>Privileges:</label>
    <select name="privileges" id="privileges" class="" onclick="craateUserJsObject.ShowPrivileges();">
        <option id="all" value="all">All</option>
        <option id="custom" value="custom">Custom</option>
    </select>
</div>
<div class="resources" style=" display: none;">resources</div>
Run Code Online (Sandbox Code Playgroud)

这个javascript是这样的:

ShowPrivileges: function() {
    var Privileges = jQuery('#privileges');
    var select = this.value;
    Privileges.change(function() {
        if (select === 'custom') {
            $('.resources').show();
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

为了工作,这应该怎么样?对不起,我知道这应该很简单,但我对这一切都很新.

dfs*_*fsq 13

你需要使用val方法:

var Privileges = jQuery('#privileges');
var select = this.value;
Privileges.change(function () {
    if ($(this).val() == 'custom') {
        $('.resources').show();
    }
    else $('.resources').hide(); // hide div if value is not "custom"
});
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/RWUdb/

  • 为什么需要第二行?该变量从不使用 (2认同)