我有一個嵌套的每個功能,想知道我怎麼可以參考this
單個項目的if語句被觸發時:如何獲取每個函數中正在迭代的當前項目?
// 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/>");
});
});
}
更新:
我花了一些時間與調試,並認識到,對於視頻縮略圖類嵌套的每個函數將迭代九倍(存在的視頻縮略圖類的數量)以及檢查每個輸入是否相同,並且因爲sameValArr幾乎總是空的,所以它在每次迭代中逐個隱藏視頻。仍在嘗試修復它...
你檢查了什麼結果'console.log(this)'? – DontVoteMeDown
@dontvotemedown我沒注意到!它確實只會返回一個視頻縮略圖。必須需要進一步的邏輯才能只定位一個視頻,而不是全部。嗯。 – TheAmazingKnight
是的,你的代碼看起來很好。你有沒有嘗試在'each'的開頭添加一個'debugger'? – DontVoteMeDown