【问题标题】:$(this) seems not properly work$(this) 似乎无法正常工作
【发布时间】:2012-07-16 17:06:29
【问题描述】:

我想单击一个 div 以显示他的孩子。 问题是我有一长串这些div。每个 div 都有一个孩子。 下面我要点击div“礼节”来显示或隐藏他的子div“detail”。

<div class="etiquette">
  <span class="date">13-07</span>
  <span class="titre">LOREM IPSUM 1</span>
     <div class="detail"><p>lorem ipsum 1</p></div>
</div>
<div class="etiquette">
  <span class="date">14-07</span>
  <span class="titre">LOREM IPSUM 2</span>
     <div class="detail"><p>lorem ipsum 2</p></div>
</div>
<div class="etiquette">
  <span class="date">14-07</span>
  <span class="titre">LOREM IPSUM 3</span>
     <div class="detail"><p>lorem ipsum 3</p></div>
</div>

我想使用的脚本是:

$(document).ready(function() {
    $(".etiquette").children(".detail").css("display", "none");
    $(this).toggle(function() {
        alert("clicked");
        $(this).children("div.detail").css("display", "block");
    }, function() {
        alert("clicked again");
        $(this).children("div.detail").css("display", "none");
    });
});

以下效果很好:

$(this).toggle(function() {
    alert("clicked");
});

以下内容也很有效。但它显示或隐藏所有 div “详细信息”,而不仅仅是单击 div 的子项:

$(this).toggle(function() {
    alert("clicked");
    $(".etiquette").children("div.detail").css("display", "block");
}, function() {
    alert("clicked again");
    $(".etiquette").children("div.detail").css("display", "none");
});
});

我做错了什么? 提前感谢您的帮助。

【问题讨论】:

    标签: jquery this children


    【解决方案1】:

    我猜你的 $(this) 指向文档本身。

    试试这个,

    $(document).ready(function() {
      $(".etiquette").children(".detail").css("display", "none");
      $(".etiquette").click(function(){
        $(this).children("div.detail").toggle();
      });
    });
    

    我没有测试代码。希望它会起作用。

    【讨论】:

      【解决方案2】:
      $(".etiquette").children(".detail").css("display", "none");
      $('.etiquette').click(function() {
          $(this).find('.detail').toggle();
      });​
      

      jsFiddle example

      关于您的代码有什么问题,有太多内容需要深入探讨,但是如果您查看这个示例,您就会明白它的作用。第一行隐藏了类 detail 的所有元素,它们是类 etiquette 的元素的子元素(你有,我保持不变)。下一个代码块将 click 事件绑定到类 etiquette 的元素上,并切换类 detail 的子元素的显示。

      【讨论】:

        【解决方案3】:

        您是否尝试过使用 .each 函数将切换函数绑定到每个 div?

        例如:

        $('.etiquette').each(function(){
          $(this).click(function(){
            //Enter toggle function here
          });
        });
        

        【讨论】:

          【解决方案4】:

          改变这个:

          $(this).toggle(function() {
          

          到:

          $('.etiquette').toggle(function() {
          

          这个this 指的是document 对象而不是.etiquette 元素。

          note: as of jQuery 1.7 using toggle mouse event has been deprecated.

          http://jsfiddle.net/f9BcB/

          【讨论】:

          猜你喜欢
          • 2017-09-04
          • 2012-05-06
          • 2013-02-17
          • 2017-10-09
          • 2017-08-03
          • 2014-05-02
          • 2011-09-11
          • 2016-02-11
          • 1970-01-01
          相关资源
          最近更新 更多