Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.2k views
in Technique[技术] by (71.8m points)

javascript - How can I show elements based on the selected option?

Isn't there a better solution than the commented if statement? I'm trying switch case but in this code, I can't hide the div so it's always existing which is wrong. I'm trying to show/hide elements depending on the selected option( it works with if statements but I think there's a cleaner way).

 <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>
            <option id="test1" value="test1">test1</option>
            <option id="test2" value="test2">tst2</option>
        </select>
    </div>
    <div class="resources" style=" display: none;">resources</div>
    <div class="test1" style=" display: none;">test1</div>
    <div class="test2" style=" display: none;">test2</div>
    <script>
    var Privileges = jQuery('#privileges');
    var select = this.value;

    **/*Privileges.change(function () {
        if ($(this).val() == 'custom') {
            $('.resources').show();
        }
        else $('.resources').hide();
    }); */**
    
    Privileges.change(function () {
    switch($(this).val()){
    case 'custom':
     $('.resources').show();
     break;
     case 'test1':
     $('.test1').show();
     break;
     case 'test2':
     $('.test2').show();
     break;
    }
    });
    </script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A more succinct way to do this would be to put a common class on all the div elements you want to toggle so that you can easily hide them on change. In addition, add another class to them which matches the value of the option of they should be displayed when selected. From there you can easily build a selector to hide/show the content. Try this:

var $privileges = jQuery('#privileges');

$privileges.on('change', e => {
  $('.content').hide().filter('.' + e.target.value).show();
});
.content {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <label>Privileges:</label>
  <select name="privileges" id="privileges">
    <option value="all">All</option>
    <option value="custom">Custom</option>
    <option value="test1">test1</option>
    <option value="test2">tst2</option>
  </select>
</div>
<div class="content custom">resources</div>
<div class="content test1">test1</div>
<div class="content test2">test2</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...