简体   繁体   English

jQuery检查是否 <li> cointains 2 img标签

[英]jQuery check if <li> cointains 2 img tags

I would like to check if the single li tag cointains single or 2 img tags and run the jQuery script only if there are 2 img tags. 我想检查单个li标签是否包含单个或2个img标签,并且仅在有2个img标签时才运行jQuery脚本。 Now when a single li contains only one image it disappear after click. 现在,当一个li仅包含一个图像时,单击后消失。

It should work follow: 它应该工作如下:

  1. On load - show first image, hide second image 加载时-显示第一张图片,隐藏第二张图片
  2. On click - First image hide, show second image 单击时-隐藏第一张图片,显示第二张图片
  3. Click on the Second image - Second image hide, show first image 单击第二张图片-隐藏第二张图片,显示第一张图片

 $(document).ready(function () { $("#list-of-images li img:first-child").click(function () { $(this).hide(); $(this).next().show(); }); $("list-of-images li img:nth-child(2)").click(function () { $(this).hide(); $(this).prev().show(); }); }); 
 #list-of-images li img:nth-child(2) { display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <ul id="list-of-images"> <li> <img src="https://cdn.infobeamer.com/s/6bd893/img/hosted-restaurant.png" /> <img src="https://cdn.infobeamer.com/s/e67487/img/hosted-your-usecase.png" /> </li> <li> <img src="https://cdn.infobeamer.com/s/6bd893/img/hosted-restaurant.png" /> <img src="https://cdn.infobeamer.com/s/e67487/img/hosted-your-usecase.png" /> </li> </ul> 

At first check the length image in clicked li . 首先,在单击的li检查长度图像。

Check if the length of next img is greater then 0 or not. 检查下一个img的长度是否大于0。 If it is true show next else show previous image. 如果为true,则显示下一个,否则显示前一个图像。

 $("#list-of-images li img").click(function () { if($(this).parent().find('img').length == 2) { $(this).hide(); if($(this).next('img').length> 0) $(this).next('img').show(); else $(this).prev('img').show(); } }); 
 #list-of-images li img:nth-child(2) { display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <ul id="list-of-images"> <li> <img src="https://cdn.infobeamer.com/s/6bd893/img/hosted-restaurant.png" /> <img src="https://cdn.infobeamer.com/s/e67487/img/hosted-your-usecase.png" /> </li> <li> <img src="https://cdn.infobeamer.com/s/6bd893/img/hosted-restaurant.png" /> <img src="https://cdn.infobeamer.com/s/e67487/img/hosted-your-usecase.png" /> </li> </ul> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM