Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
查找列表中多个元素的位置(jQuery)_Jquery - Fatal编程技术网

查找列表中多个元素的位置(jQuery)

查找列表中多个元素的位置(jQuery),jquery,Jquery,我有几个图像的列表,一些带有肖像类,另一些带有风景类: <img src="/images/fullsize/007.jpg" class="portrait"> <img src="/images/fullsize/008.jpg" class="landscape"> <img src="/images/fullsize/047.jpg" class="landscape"> <img src="/images/fullsize/048.jpg" c

我有几个图像的列表,一些带有肖像类,另一些带有风景类:

<img src="/images/fullsize/007.jpg" class="portrait">
<img src="/images/fullsize/008.jpg" class="landscape">
<img src="/images/fullsize/047.jpg" class="landscape">
<img src="/images/fullsize/048.jpg" class="landscape">
<img src="/images/fullsize/049.jpg" class="landscape">
<img src="/images/fullsize/050.jpg" class="portrait">
<img src="/images/fullsize/051.jpg" class="portrait">
<img src="/images/fullsize/052.jpg" class="landscape">
<img src="/images/fullsize/053.jpg" class="landscape">
<img src="/images/fullsize/054.jpg" class="landscape">


如何识别所有.肖像图像的位置(在列表中)并将其作为数组存储在变量中?(即,对于本例,我需要输出“1、6、7”或“0、5、6”。)。我研究了如何使用.index(),但它似乎只返回一个结果。

看看这个例子:

$(function() {

  var p_ind =[], l_ind=[];

  $('img').each(function(i, data) {
    if( $(data).hasClass('portrait') ) p_ind.push(i);
    else l_ind.push(i);
  });

  // Portrait
  console.log(p_ind);

  // Landscape
  console.log(l_ind);
});
下面是一个示例,其中包含一些示例代码,说明了一个可能的示例:

$(function() {
    var portrait = [];
    var landscape = [];
    $("img").each(function (i, item) {
        if ($(item).hasClass("portrait")) {
            portrait.push(i);
        }
        if ($(item).hasClass("landscape")) {
            landscape.push(i);
        }
    });
    console.log("Portrait: " + portrait);
    console.log("Landscape: " + landscape);
});

它使用jQuery选择器选择图像,然后针对每个图像询问它是否包含纵向或横向类。根据这些问题的答案,它们会被放入数组中供以后检查。

这应该很简单,只要循环所有元素并将每个“正确”元素的索引添加到数组中即可。谢谢,这非常有效!我还没有接触到循环的概念(我对JavaScript非常陌生),所以这非常有用。