Jquery $(this)子选择器 [英] Jquery $(this) Child Selector

查看:154
本文介绍了Jquery $(this)子选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个页面上使用:

jQuery('.class1 a').click( function() {
  if ($(".class2").is(":hidden")) {
    $(".class2").slideDown("slow");
  } else {
    $(".class2").slideUp();
  }
});

稍后页面中的结构如下:

With a structure in the page later that goes like this:

<div class="class1">
  <a href="...">text</a>
  <div class="class2">text</div>
</div>

这很好用,除非你有多个class1 / class2集合:

This is working fine, except when you have multipule class1/class2 sets like so:

<div class="class1">
  <a href="...">text</a>
  <div class="class2">text</div>
</div>
<div class="class1">
  <a href="...">text</a>
  <div class="class2">text</div>
</div>
<div class="class1">
  <a href="...">text</a>
  <div class="class2">text</div>
</div>

如何更改初始jquery代码,使其只影响当前class1下的class2点击?我尝试了此页面上推荐的变体: $(this)selector和children?但是havent得到它工作

How do I change the initial jquery code so that it only effects the class2 under the current class1 that was clicked? I've tried variations of what was recommended on this page: $(this) selector and children? but havent gotten it to work yet

推荐答案

使用HTML的最好方法可能是使用< a href =http://docs.jquery.com/Traversing/next#expr =noreferrer> next 功能,如下所示: / p>

The best way with the HTML you have would probably be to use the next function, like so:

var div = $(this).next('.class2');

由于点击处理程序发生在< a> ,你也可以遍历到父DIV,然后向下搜索第二个DIV。您可以使用 parent children 。如果你放置的HTML不完全相同,第二个DIV可能位于链接的另一个位置,这种方法将是最好的:

Since the click handler is happening to the <a>, you could also traverse up to the parent DIV, then search down for the second DIV. You would do this with a combination of parent and children. This approach would be best if the HTML you put up is not exactly like that and the second DIV could be in another location relative to the link:

var div = $(this).parent().children('.class2');

如果您希望搜索不限于直接子女,请使用 find 而不是

If you wanted the "search" to not be limited to immediate children, you would use find instead of children in the example above.

此外,如果可能,最好使用标签名来预先添加类选择器。即,如果只有< div> 标签将具有这些类,则使选择器 div.class1 div.class2

Also, it is always best to prepend your class selectors with the tag name if at all possible. ie, if only <div> tags are going to have those classes, make the selector be div.class1, div.class2.

这篇关于Jquery $(this)子选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆