【问题标题】:jquery next() thisjquery next() 这个
【发布时间】:2023-03-08 01:03:02
【问题描述】:

我偶然发现了一个小问题。

尝试制作一个简单的手风琴导航。使用 jquery,但注意到一些我无法弄清楚的事情。

这是我的代码

<div class="box"> Item 1</div>
<div class="text"> Text Box </div>
<div class="box"> Item 2</div>
<div class="text"> Text Box 2</div>
<div class="box"> Item 3</div>
<div class="text"> Text Box 3</div>

JS

$('.box').click(function(){
    $('.text').slideUp()
    $(this).next().slideToggle()    
})

我想知道的是,如果我使用

    $(this).next().slideToggle()      

一切正常。

现在我尝试替换(this)如下:

    $('.text').next().slideToggle() 

但效果不同。 我认为 (this) 会与 div-text 或至少与 DOM 中的其他内容有关?

【问题讨论】:

    标签: jquery this next


    【解决方案1】:

    点击事件中的$(this)代表事件源,而$('.text')代表所有具有class文本的元素的集合。 $('.text').next().slideToggle() 将在选择器 $('.text') 返回的集合的第一个元素上调用 slideToggle

    【讨论】:

    • 感谢您的快速回放和出色的回答。但是你不是说你的最后一句话 $(this).next().slideToggle() 会在选择器 $('.text') 返回的集合的第一个元素上调用 slideToggle 吗?
    【解决方案2】:

    简而言之:

    $(this) // <----Represents current target which got the event
    

    同时:

    $('.text') // <--- this is a collection of all elems with class '.text' so all
               // -----will be getting events simultaneosly.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-23
      • 2011-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-28
      相关资源
      最近更新 更多