如何找到左右点击项目的图像标签数量?

时间:2018-02-19 08:37:23

标签: jquery

假设我有4张图片:

<form>
<img class="image" src="/imge1.jpg"/>
<img class="image" src="/imge2.jpg"/>
<img class="image" src="/imge3.jpg"/>
<img class="image" src="/imge4.jpg"/>
</form>

如果单击1张图像,是否可以知道所点击图像的图像数量和点击图像的图像数量?

例如,如果我点击图像2,我应该左边= 1右边= 2 对于图像3对= 1左= 2。

4 个答案:

答案 0 :(得分:3)

尝试使用prevAll()和nextAll()查看已点击的元素,如代码段所示。

&#13;
&#13;
$(".image").on("click", function(e){
  console.log("Left: " + $(this).prevAll("img").length);
  console.log("Right: " + $(this).nextAll("img").length);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <p>Whats this? A parapgraph?!</p>
  <img class="image" src="/imge1.jpg"/>
  <img class="image" src="/imge2.jpg"/>
  <img class="image" src="/imge3.jpg"/>
  <img class="image" src="/imge4.jpg"/>
</form>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以简单地结合使用.index()和父母img子女的长度:

$(this).index()将为您提供单击左侧img的数量。

$(this).parent().children('img').length - $(this).index() - 1会将img的号码提供给点击后的$('img').on('click',function(){ console.log('There are '+($(this).index())+' cat(s) to the left'); console.log('There are '+($(this).parent().children('img').length - $(this).index() - 1)+' cat(s) to the right'); });

&#13;
&#13;
img{
  width: 50px;
  height: 50px;
  object-fit: cover;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <img class="image" src="http://www.catster.com/wp-content/uploads/2017/08/A-fluffy-cat-looking-funny-surprised-or-concerned.jpg" />
  <img class="image" src="https://upload.wikimedia.org/wikipedia/commons/3/3a/Cat03.jpg" />
  <img class="image" src="http://www.catster.com/wp-content/uploads/2017/06/small-kitten-meowing.jpg" />
  <img class="image" src="https://www.petmd.com/sites/default/files/petmd-cat-happy.jpg" />
</form>
&#13;
{{1}}
&#13;
&#13;
&#13;

答案 2 :(得分:0)

你可以使用jquery prevAll();和nextAll();

    $('.image').click(function){
    console.log($.prevAll('.image').length);
    console.log($.nextAll('.image').length);
});

答案 3 :(得分:0)

检查,

$('.image').click(function(){
var left = $(this).prevAll().length -1;
var right = $(this).nextAll().length -2;
alert("On your left : " + left + "  on your right: " + right);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<img class="image" src="/imge1.jpg"/>
<img class="image" src="/imge2.jpg"/>
<img class="image" src="/imge3.jpg"/>
<img class="image" src="/imge4.jpg"/>