简体   繁体   English

选择子级的父级(如果有)

[英]Selecting the parent of a child if it has a class

I have been trying to change some things with the Flexslider v2 to fit my needs. 我一直试图用Flexslider v2改变一些东西以满足我的需求。 I have been trying to use jQuery to target the parent li of the img class="active" because i want to give it a class of selected but I have not been very successful 我一直在尝试使用jQuery来定位img class="active"的父li ,因为我想给它一个selected的类,但我还没有很成功

<ol class="foo">
  <li>
    <img src="bar.png" class="active">  <-- This class changes img elements depending on the active slide
  </li>
  <li>
    <img src="bar.png">
  </li>
  <li>
    <img src="bar.png">
  </li>
</ol>

I came up with something like this: 我提出了这样的事情:

$(document).ready(function() {
   $('.foo li').children().each(function(index, value) {
     if($(value).hasClass('active')) {
         $(this).parent('li').addClass('selected');
     } else {
         $(this).parent('li').removeClass('selected');
     }
  });
});

and it works in the console, but it does nothing within my main.js file. 它在控制台中工作,但它在我的main.js文件中没有任何作用。

LIVE DEMO 现场演示

Simple like one line: 简单就像一行:

$('.foo li').find('img.active').closest('li').addClass('selected');

Or if you really need it: 或者,如果你真的需要它:

LIVE DEMO 现场演示

$('.foo li').find('img').each(function(index, el) {
    if($(el).hasClass('active')) {
        $(el).closest('li').addClass('selected');
    } else {
        $(el).closest('li').removeClass('selected');
    }
});

jQuery API Documentation - Closest jQuery API文档 - 最近

Wrap it i document.ready like this in your main.js and then it should work as expected. 把它包装好我的文件。你的main.js就像这样,然后它应该按预期工作。 You got it worked in console because all elements are loaded when you runt the script. 你得到它在控制台中工作,因为当你破坏脚本时所有元素都被加载。

$(function(){
    $('.foo li').children().each(function(index, value) {
      if($(value).hasClass('active')) {
          $(this).parent('li').addClass('selected');
      } else {
         $(this).parent('li').removeClass('selected');
      }
  });
});

使用nearest():

$(this).closest('li'),addClass('selected');

Add $(document).ready(function(){ 添加$(document).ready(function(){

$(document).ready(function(){
$('.foo li').children().each(function(index, value) {
    if($(value).hasClass('active')) {
        $(this).parent('li').addClass('selected');
    } else {
        $(this).parent('li').removeClass('selected');
    }
});
    });

Check the similar question HERE 这里检查类似的问题

$('.foo > li').removeClass('selected').each(function() {
    if($(this).find('img').hasClass('active')) {
        $(this).addClass('selected');
    }
});

Why use .each() ? 为什么要使用.each() When we can achieve our goal without it. 当我们没有它就能实现我们的目标。

$(".foo li img.active").parent().addClass("selected");

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

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