2016-03-15 2 views
0

Я вложенный каждую функцию и хочу знать, как я могу сослаться на this одного элемента, когда срабатывает, если заявление:Как получить текущий элемент, повторяющийся в каждой функции?

// check if array is empty 
if(sameValArr.length === 0) 
{ 
    $(this).hide(); // hide current video thumbnail item 
} 
else // not empty 
{ 
    $(this).show(); // show current video tbumbnail item 
} 

также пытался:
$(item).hide();
$(item[i]).hide();

В настоящее время, это спрятав все видео с именем класса .video-thumbnail сразу, и я хочу только скрыть только те, которые повторяются, а не все.

Полная функция:

// check every time the user checks/unchecks inputs to show/hide the video 
function checkboxChanged(videoTags) 
{ 
    var checkedAttr = []; // array for checked attributes 
    // change event listener for whenever one or more of the following checkboxes have been checked/unchecked 
    $('#category-list :checkbox').change(function() 
    { 
     checkedAttr = []; // refresh and initialize new array values 
     $('#category-list :checkbox').each(function(i, item) // loop thru the input checkboxes 
     { 
      if($(item).is(':checked')) // item is checked 
      { 
       checkedAttr.push($(item).val()); // add it to array 
      } 
     }); 
     console.log("checkedAttr: ", checkedAttr); 
     console.log("init videoTags: ", videoTags); 


     // loop through each of the thumbnails to see if video tags match those in checkedAttr array 
     $('.video-thumbnail').each(function(i, item) 
     { 
      console.log(i + " videoTags: ", videoTags); 

      // TODO: 
      // 1. compare the two arrays if there's any matching values in both 
      // 2. if yes, store the matching value in a new array; otherwise do nothing 
      // 3. check the new array if it isn't empty 
      // 4. if empty, hide the video; if not empty do nothing (show video) 
      var sameValArr = []; // refresh array values 
      console.log("INTERSECT: ", arrayIntersection(checkedAttr, videoTags));  // print resulting array intersection 
      sameValArr = arrayIntersection(checkedAttr, videoTags); // store same matching array intersection values 

      // check if array is empty 
      if(sameValArr.length === 0) 
      { 
       $(this).hide(); // hide current video thumbnail item 
      } 
      else // not empty 
      { 
       $(this).show(); // show current video thumbnail item 
      } 
      console.log("<br/>"); 
     }); 
    }); 
} 

Update:

Я провел несколько моментов с отладчиком и понял, что вложенные каждая функция для класса видео миниатюр будет повторяться в девять раз (количество присутствующих классов миниатюр видео), а также проверка каждого входа, если они одинаковы, и поскольку sameValArr почти всегда пуст, он скрывает видео по одному на каждой итерации. Все еще пытаюсь это исправить ...

+0

Вы проверили, какие результаты 'console.log (this)'? – DontVoteMeDown

+0

@dontvotemedown Я этого не замечал! Он возвращает только одно миниатюру видео. Должна потребоваться дополнительная логика, предназначенная только для одного видео, а не для всех. Хммм. – TheAmazingKnight

+0

Да, ваш код кажется прекрасным. Вы пытались добавить «отладчик» в начале «каждого»? – DontVoteMeDown

ответ

1

Использование предмета, прошедшего для вас, item.

 $('.video-thumbnail').each(function(i, item) 
     { 
      console.log(i + " videoTags: ", videoTags); 

      // TODO: 
      // 1. compare the two arrays if there's any matching values in both 
      // 2. if yes, store the matching value in a new array; otherwise do nothing 
      // 3. check the new array if it isn't empty 
      // 4. if empty, hide the video; if not empty do nothing (show video) 
      var sameValArr = []; // refresh array values 
      console.log("INTERSECT: ", arrayIntersection(checkedAttr, videoTags));  // print resulting array intersection 
      sameValArr = arrayIntersection(checkedAttr, videoTags); // store same matching array intersection values 

      // check if array is empty 
      if(sameValArr.length === 0) 
      { 
       $(item).hide(); // hide current video thumbnail item 
      } 
      else // not empty 
      { 
       $(item).show(); // show current video thumbnail item 
      } 
      console.log("<br/>"); 
     }); 
+0

'this' представляет тот же объект, что и элемент. – DinoMyte

+0

Я получил его работу с помощью 'item' или' this', поскольку, как оказалось, я добавил 'return false', чтобы действовать оператор break внутри оператора if-else, чтобы вытеснить его из цикла, и это сработало, но это породило еще больше проблем (например, скрытие первой миниатюры видео, а не намеченной). В каком-то смысле это все равно пытается сделать все. – TheAmazingKnight

 Смежные вопросы

  • Нет связанных вопросов^_^