【问题标题】:jQuery select option show / hide for multiple elementsjQuery选择选项显示/隐藏多个元素
【发布时间】:2013-08-24 22:29:35
【问题描述】:

您好,我有这段代码用于通过选择选项显示和隐藏元素,它适用于 1 个元素,但如果我将它与更多元素一起使用,它就不再正确了。我怎样才能修改它,使其适用于每个元素?

$(document).ready(function (e) {

    var $targets = $(".open_times");

    $(".pr_opener").change(function () {
        var i = $('option:selected', this).index();
        $targets.show().eq(i).hide();
    });
});

http://jsfiddle.net/6yv4g/1/

【问题讨论】:

    标签: jquery select hide show


    【解决方案1】:

    看到这个demo

    $(document).ready(function (e) {
    
        var $targets = $(".open_times");
    
        $(".pr_opener").change(function () {
            var i = $('option:selected', this).text();
            if (i=='Open') {
                $(this).closest("li").next(".open_times").show();
            } else {
                $(this).closest("li").next(".open_times").hide();
            }
        });
    });
    

    【讨论】:

      【解决方案2】:

      您可以将其简化为:

      $(".pr_opener").change(function () {
          $(this).parent().next('div.open_times').toggle( this.value == 'Open' );
      });
      

      另外,您需要修复标记(您没有正确关闭任何 <select> 元素)

      Here's a fiddle

      【讨论】:

      • 感谢您的关注!
      【解决方案3】:

      让事件传播到ul 然后处理它。

      $(document).ready(function (e) {
          $("#pr_times ul").on("change",function () {
              $(".open_times", this).toggle();
          });
      });
      

      JS 小提琴: http://jsfiddle.net/6yv4g/5/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-24
        • 1970-01-01
        • 2017-12-24
        • 2011-02-08
        • 1970-01-01
        相关资源
        最近更新 更多