我用这个:

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

On page structure:

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

仅当您没有多个class1/class2集时才有效,例如:

<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?我try 了How to get the children of the $(this) selector?条建议,但没有成功.

推荐答案

使用HTML的最佳方法可能是使用next函数,如下所示:

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

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而不是上面示例中的children.

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相关问答推荐

可以推迟 jQuery 的加载吗?

jQuery找到最近的匹配元素

如何使用 JQuery Select 没有特定子元素的元素

jQuery / Ajax - $.ajax() 将参数传递给回调 - 使用好的模式?

删除所有子元素的 CLASS

按百分比zoom div的内容?

如何使div全屏?

JQuery .hasClass 用于 if 语句中的多个值

所有选中复选框的 jQuery 数组(按类)

使用 jQuery 获取选定的选项 id

在 JQuery .trigger 上传递参数

jQuery 如果 div 包含此文本,则替换该部分文本

如何在javascript中获取json键和值?

如何在 JavaScript 中的对象数组中查找值?

如何删除/更改 JQuery UI 自动完成助手文本?

使用 Jquery 查找父 div 的 id

JavaScript 等效于 jQuery 的扩展方法

使用 jQuery 将事件侦听器添加到动态添加的元素

使用 Chosen 插件更改 Select 中的 Select

jQuery 将换行符转换为 br (nl2br 等效)