[英]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: 它应该工作如下:
$(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.