【发布时间】:2016-07-01 08:18:29
【问题描述】:
我有一个嵌套的 each 函数,想知道在触发 if 语句时如何引用 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/>");
});
});
}
更新:
我在调试器上花了一些时间,并意识到视频缩略图类的嵌套每个函数将被迭代多达 9 次(存在的视频缩略图类的数量),同时检查每个输入是否相同,并且因为 sameValArr几乎总是空的,它在每次迭代中一个一个地隐藏视频。仍在尝试修复它...
【问题讨论】:
-
你检查了
console.log(this)的结果吗? -
@dontvotemedown 我没注意到!它只返回一个视频缩略图。必须需要进一步的逻辑才能仅针对一个视频而不是全部。嗯。
-
是的,您的代码看起来不错。您是否尝试在
each的开头添加debugger? -
@dontvotemedown 是的,在使用控制台进行挖掘之后,我在 if 语句中添加了
return false并强制它退出循环,但它隐藏了错误的视频......第一个视频,所以从某种意义上说,它仍然贯穿所有,而不是每个语句中指定的那个。不知何故,它触发了每个视频的 if 语句,我再也无法让它显示了。 -
考虑为您的问题创建一个 jsfiddle.com ......它将帮助您自己获得一个好的答案
标签: javascript jquery loops this each