简体   繁体   English

jQuery父母选择器-遍历

[英]jQuery parents selector - traversing

I have an array that inserts articles. 我有一个插入文章的数组。 When I click the h3 (which has the title) I want to display more information based on the article's index. 当我单击h3(带有标题)时,我想根据文章的索引显示更多信息。 I think I need to go up to the <section id="main"> to find the index of the <article> I clicked on starting from my <h3> . 我想我需要去<section id="main">来找到我从<h3>开始单击的<article>的索引。

Here's my HTML: 这是我的HTML:

    <section id="main" class="container">
      <article class="article">
        <section class="featuredImage">
          <img src="images/article_placeholder_1.jpg" alt="" />
        </section>
        <section class="articleContent">
            <a href="#"><h3>Test article title</h3></a>
            <h6>Lifestyle</h6>
        </section>
        <section class="impressions">
          526
        </section>
        <div class="clearfix"></div>
      </article>
    </section>

Here is my attempt of getting the index: 这是我获取索引的尝试:

$('.articleContent a').on('click', function(e) {
    var $target,
        $parent,
        $index;
    e.preventDefault();

    $target = $(e.target);
    $parent = $target.parents('.main');
    $index = $parent.find('.article').index();
    console.log($index);
});

Your HTML nesting structure is the following 您的HTML嵌套结构如下

section#main > article.article > section.articleContent > a

You have to search ascendants for more than one level up, so parent() is not enough. 您必须搜索上升的一个以上的层次,所以parent()是不够的。

parents() on the other side can travel for more than one parent and by passing a selector, you can filter the parents. 另一方面, parents()可以旅行多个父母,并且通过传递选择器可以过滤父母。

$('.articleContent a').on('click', function(e) {
    e.preventDefault();
    var index = $(this).parents('.article').first().index();
    console.log(index);
});

So this will find the first element with the class "article". 因此,这将找到类“ article”的第一个元素。 Notice you could also be more specific, by using the selector "article.article" 注意,通过使用选择器“ article.article” ,您也可以更加具体

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

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