javascript - 根据选择的选择显示 3 个 div 之一

标签 javascript jquery html css

<分区>

我有一个带有 3 个选项 body、strength、distance 的选择框。我想使用 javascript/jquery 来显示一个 div,具体取决于选择了哪些选项。到目前为止,我只是让它在按钮上工作 http://codepen.io/Irish1/pen/iwKam

html

<form>
  <p>
    <label for="select">
      Goal Type
    </label>
    <select class="typeselect">
      <option value=""></option>
      <option value="body">
        Body
      </option>
      <option value="strength">
        Strength
      </option>
      <option value="distance">
        Distance
      </option>
    </select>
    <button class="toggle">push</button>
  </p>
  <div class="body">
    <p>
      <label for="body">
       Body
      </label>
    </p>
  </div>
  <div class="strength">
    <p>
      <label for="strength">
        Strength
      </label>
    </p>
  </div>
  <div class="distance">
    <p>
      <label for="distance">
       Distance
      </label>
    </p>
  </div>


</form>

CSS

.body {
  display: none;
}

.strength {
  display: none;
}

.distance {
  display: none;
}

JavaScript

$('.toggle').click(function(){
  $('.body').toggle();
});

最佳答案

尝试

//dom ready handler
jQuery(function () {
    //all the elements that has to be shown/hidden, it is cached for easy access later
    var $targets = $('.body, .strength, .distance');

    //chang handler for the select element
    $('.typeselect').change(function () {
        //hide previously displayed elements
        $targets.hide()

        //find the element with the selected option's value as class, if empty option is selected set it to an empty set
        if (this.value) {
            $('.' + this.value).show()
        }
    })
})

演示:Fiddle

如果你想让按钮处理程序工作,那么

//dom ready handler
jQuery(function () {
    //all the elements that has to be shown/hidden, it is cached for easy access later
    var $targets = $('.body, .strength, .distance');

    var $select = $('.typeselect');

    //click handler for the button
    $('.toggle').click(function (e) {
        //prevent the default form action of the button click
        e.preventDefault();

        //hide previously displayed elements
        $targets.hide()

        //selected value
        var val = $select.val();
        //find the element with the selected option's value as class, if empty option is selected set it to an empty set
        if (val) {
            $('.' + val).show()
        }
    })
})

演示:Fiddle

关于javascript - 根据选择的选择显示 3 个 div 之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20747802/

相关文章:

javascript - 预填充输入文本框

javascript - ie10支持从剪贴板粘贴图片吗?

javascript - 如何在 Android WebView 中启用 jQuery 点击事件

javascript - ReactJS ES6 函数绑定(bind) - 未捕获的类型错误 : Cannot read property 'update' of undefined

javascript - 如何在 IE8 中停止事件传播

javascript - 将文本添加到从外部 JS 加载的字段

javascript - 在 .live 函数中触发 href 事件

javascript - 为列表项导航淡出旧图像并淡入新图像

html - header背景图片在ie6,ie7,ie8上不显示

javascript - 多图片src路径切换