简体   繁体   English

选择不是父母的最近的班级

[英]Selecting nearest class that isn't a parent

I'm trying to select the header text for a clicked item using jquery/javascript. 我正在尝试使用jquery / javascript选择单击项的标题文本。 I'm having an issue writing the proper selectors given the fact that the item clicked isn't a descendant of the header section. 考虑到单击的项目不是标题部分的后代,因此编写适当的选择器时遇到问题。 For example, if I click item3.1, I want it to return the text "Header 3". 例如,如果我单击item3.1,我希望它返回文本“ Header 3”。

<section class="mainclass">
  <section class="header">Header 1</section>
  <ul>  
    <li>item1.1</li>
    <li>item1.2</li>
    <li>item1.3</li>
  </ul>
 <section class="header">Header 2</section>
 <ul>  
   <li>item2.1</li>
   <li>item2.2</li>
   <li>item2.3</li>
 </ul>
 <section class="header">Header 3</section>
 <ul>  
   <li>item3.1</li>
   <li>item3.2</li>
   <li>item3.3</li>
 </ul>
 <section class="header">Header 4</section>
</section>

Current code example: 当前代码示例:

jQuery('body').on('click','li',function(e) {
if (jQuery(this).parent('header').length <= 0){
    alert(jQuery(this).closest('mainclass').find('header').text());
}
});

This code sample returns all the headers. 此代码示例返回所有标头。 I haven't been able to get this to work with variants of closest, parents, find, etc. 我还无法使它与最亲密的,父母的,发现的等一起工作。

Use .prev() to get the element just before a selection. 使用.prev()在选择之前获取元素。 So go up to the <ul> , then go back one element to get the header. 因此,转到<ul> ,然后返回一个元素以获取标头。 Also, you need a . 另外,您需要一个. to match a class. 匹配一个班级。

 jQuery('body').on('click', 'li', function(e) { console.log(jQuery(this).closest('ul').prev('.header').text()); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <section class="mainclass"> <section class="header">Header 1</section> <ul> <li>item1.1</li> <li>item1.2</li> <li>item1.3</li> </ul> <section class="header">Header 2</section> <ul> <li>item2.1</li> <li>item2.2</li> <li>item2.3</li> </ul> <section class="header">Header 3</section> <ul> <li>item3.1</li> <li>item3.2</li> <li>item3.3</li> </ul> <section class="header">Header 4</section> </section> 

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

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