gpt4 book ai didi

jquery - 如何像另一个一样使用同一个类切换单个元素

转载 作者:太空宇宙 更新时间:2023-11-04 14:58:02 25 4
gpt4 key购买 nike

我有这样的 HTML 代码:

<img src="img.png" class="arrow"><h2 class="title">Heading 1</h2>
<p class="intro">Lorem Ipsum 1</p>

<img src="img.png" class="arrow"><h2 class="title">Heading 2</h2>
<p class="intro">Lorem Ipsum 2</p>

<img src="img.png" class="arrow"><h2 class="title">Heading 3</h2>
<p class="intro">Lorem Ipsum 3</p>

如果我单击第一个 img 元素,我想切换“介绍”类,但仅限第一个元素。如果我单击第二个 img,切换第二个“介绍”等。我如何在 jQuery 中执行此操作? (“介绍”有 display:none; 在 CSS 中)。我试过选择伪类:

$(".intro:first-child").click(function() {
$("intro:first-child").toggle();
}

但它不起作用。也许我应该使用 id (id="intro-1", "intro-2", etc) 而不是 class 并在 jQuery 中分别选择每个元素?

最佳答案

使用 nextAll() 方法和 :first 伪类选择器。将点击事件处理程序附加到 img 标记,内部处理程序 this 引用被点击的元素 dom 对象。

// attach click event handler to all img tag
$(".arrow").click(function() {
// get first `.intro` after the clicked img tag
$(this).nextAll('.intro:first').toggle();
})

$(".arrow").click(function() {
$(this).nextAll('.intro:first').toggle();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="img.png" class="arrow">
<h2 class="title">Heading 1</h2>
<p class="intro">Lorem Ipsum 1</p>

<img src="img.png" class="arrow">
<h2 class="title">Heading 2</h2>
<p class="intro">Lorem Ipsum 2</p>

<img src="img.png" class="arrow">
<h2 class="title">Heading 3</h2>
<p class="intro">Lorem Ipsum 3</p>

关于jquery - 如何像另一个一样使用同一个类切换单个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38889665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com