0

I have been trying to change some things with the Flexslider v2 to fit my needs. 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

<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.

4

6 に答える 6

1

LIVE DEMO

一行のように単純:

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

または、本当に必要な場合:

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

于 2013-02-28T12:07:08.017 に答える
1

これを document.ready のように main.js にラップすると、期待どおりに動作するはずです。スクリプトを実行するとすべての要素が読み込まれるため、コンソールで機能しました。

$(function(){
    $('.foo li').children().each(function(index, value) {
      if($(value).hasClass('active')) {
          $(this).parent('li').addClass('selected');
      } else {
         $(this).parent('li').removeClass('selected');
      }
  });
});
于 2013-02-28T12:08:00.263 に答える
0

最も近い () を使用します。

$(this).closest('li'),addClass('selected');
于 2013-02-28T12:07:19.347 に答える
0

追加$(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');
    }
});
    });

ここで同様の質問を確認してください

于 2013-02-28T12:09:49.887 に答える
0
$('.foo > li').removeClass('selected').each(function() {
    if($(this).find('img').hasClass('active')) {
        $(this).addClass('selected');
    }
});
于 2013-02-28T12:12:19.443 に答える
0

.each()を使用する理由 それなしで目標を達成できるとき。

$(".foo li img.active").parent().addClass("selected");
于 2013-02-28T12:13:02.837 に答える