【问题标题】:Why do jQuery display&hide effects only work with embedded css display:none?为什么 jQuery 显示和隐藏效果仅适用于嵌入式 css 显示:无?
【发布时间】:2023-04-02 05:31:01
【问题描述】:

我有几个 .handlebars 模板加载到车把默认布局中,使用车把作为 node.js 的视图引擎

模板使用 {{{ body }}} html 转义加载到 body 标记中:

<body>
{{{ body }}}
</body>

当涉及模板中的 div 时..为什么 jQuery 显示/隐藏效果会这样工作:

<label class="btn">
  <input type="checkbox" id="theBtn"> theBtn
</label>

..a bunch of html..

<div class="theDiv" style="display:none;"></div>

$(document).ready(function () {
  $("#theBtn").change(function() {
       $(".theDiv").slideToggle(); 
  });
});

但这种方式只有在 HTML 直接以默认布局而不是模板编写时才有效:

.hide {
display: none;
}

<label class="btn">
  <input type="checkbox" id="theBtn"> theBtn
</label>

..a bunch of html..

<div class="theDiv hide"></div>

$(document).ready(function () {
  $("#theBtn").on('click', function () {
      var $when = $(".theDiv");
      $when.slideToggle();
      $(".theDiv").not($when).slideUp();
  });
});

【问题讨论】:

    标签: javascript jquery html css handlebars.js


    【解决方案1】:

    我认为您为 input 元素复制了 id。由于id 必须是唯一的,因此您需要使用类来代替:

    <input type="checkbox" class="theBtn" />
    

    之后,您只需定位您点击的input的父标签的前一个兄弟.theDiv,目前您已经定位了所有.div,因此您可以使用:

    var $when = $(this).parent().prev();
    

    代替:

    var $when = $(".theDiv");
    

    Fiddle Demo

    【讨论】:

    • theBtn 是整个范围内唯一的#theBtn id.. 想使用定位方法,因为会有多个 .theDiv 元素.. 但在 #theBtn 和 . theDiv,用于格式化等......还有其他建议吗?
    【解决方案2】:


    jQuery

    $(document).ready(function () {
        $(document).on("change","#theBtn",function () {
            var $when = $(".theDiv");
            $when.slideToggle();
            $(".theDiv").not($when).slideUp();
        });
    });  
    

    希望这就是你要找的……!!

    【讨论】:

    • 嗯,是的,但这在把手模板中不起作用.. 感谢您的回答
    • 你为什么不使用把手模板创建一个小提琴.. @StackThis 看到更新的答案.. jQuery.on() 可能是解决方案你的问题..
    • 如何设置 Fiddle 以模拟在默认布局中插入 .handelbars 模板?这是服务器端操作。是否有客户端等效项?感谢您对此的想法..
    • 一切都好..否则会摆弄..问题确实出在 .hide vs. style="display:none;" ...无论出于何种原因,外部css的类定义仅在html字面上位于主布局中时才有效,当html在模板中时,只有嵌入式样式有效..只是想知道为什么..
    • @StackThis 制作Handlebar Fiddle 是可能的...只是显示使用从服务器检索到的JSON...。
    猜你喜欢
    • 2022-01-16
    • 1970-01-01
    • 2020-09-21
    • 2015-04-29
    • 1970-01-01
    • 1970-01-01
    • 2016-04-10
    • 1970-01-01
    • 2015-06-05
    相关资源
    最近更新 更多