简体   繁体   English

使用相同类的jQuery click函数

[英]jQuery click function using same classes

I have a dropdown function that I need to work only on the div clicked, not all (I have 14+ of the same classes on the page that need to be displayed when a certain one is clicked) 我有一个下拉功能,我只需要在单击的div上工作,而不是全部(单击某个特定的div时,我必须在页面上显示14个以上的相同类)

At the moment my jQuery is as follows. 目前,我的jQuery如下。

$('.qacollapsed').hide();
$('.qa').click(function () {
    $('.qacollapsed').slideToggle();
    $(this).toggleClass('active');
});

Of course, that is toggling all qacollapsed classes when there is 14 on the page (Q&A) 当然,如果页面上有14个(Q&A),那将切换所有qacollapsed类

Is there a way for it to only drop down the one that is clicked? 有没有办法只将被点击的下拉列表?

the HTML HTML

<div class="qa">
<h4 class="question"> </h4>
</div>

<div class="qacollapsed">
<p>  </p>
</div>

Yo could find() it or use this as a context in the selector to choose only a descendent of the clicked object 可以在选择器中使用find()或将this用作上下文来选择被单击对象的后代

$('.qa').click(function () {
    $('.qacollapsed', this).slideToggle();
    //You could do $(this).find('.qacollapsed').slideToggle();
    $(this).toggleClass('active');
});

It would be helpful to provide a snippet of HTML here, but I'll take a guess at the structure of your markup for now.. 在此处提供HTML片段将很有帮助,但现在我将对您的标记结构进行猜测。

Instead of referencing all .qacollapsed elements, you need find elements that are close to the .qa that was clicked, eg: 而不是引用所有.qacollapsed元素,您需要查找与单击的.qa接近的元素,例如:

$('.qa').click(function () {
   $(this)                     // start with the clicked element
       .find('.qacollapsed')   // find child .qacollapsed elements only
       .slideToggle();
   $(this).toggleClass('active');
});

This will work if .qacollapsed is inside .qa - if not, you might need to use next (for siblings), or one of the other jQuery tree traversal methods . 如果.qacollapsed位于.qa ,则此方法将起作用-否则,您可能需要使用next (用于同级)或其他jQuery树遍历方法之一

查看jQuery选择器 ,为什么不只使用$(this)

$('.qacollapsed').hide();
$('.qa').click(function () {
    $(this).toggleClass('active').next().slideToggle();
});

Personally, I'd give all the divs IDs, the clickable bit being the ID of the question in the database for example, and the answer just being id='ID_answer' or something, then use jquery to slide in the div with the id corresponding to the link clicked, ie 就个人而言,我会给所有div ID,例如,可点击位是数据库中问题的ID,答案只是id ='ID_answer'之类的东西,然后使用jquery在带有ID的div中滑动对应于单击的链接,即

 Var showIt = $(this).attr('id') + '_answer'
 $('.qacollapsed').not('#'+showIt).hide();
 $('#'+showIt).slideToggle;

That will hide all the divs without that ID and show the required one. 这将隐藏所有没有该ID的div,并显示所需的ID。

Dexter's use of .next above looks simpler though, I've not tried that as being relatively new to jquery too. 尽管Dexter在.next上面的用法看起来更简单,但我也没有尝试过将它作为jquery的新手。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM