我想检查单个 li
标签是否包含单个或 2 个 img
标签,并仅在有 2 个 img
时运行 jQuery 脚本> 标签。现在,当单个 li
仅包含一张图像时,它会在单击后消失。
它应该按照以下方式工作:
- 加载时 - 显示第一张图片,隐藏第二张图片
- 点击时 - 第一张图片隐藏,显示第二张图片
- 点击第二张图片 - 第二张图片隐藏,显示第一张图片
$(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>
最佳答案
首先检查点击的li
中的长度图像。
检查下一个img
的长度是否大于0。如果为 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>
关于javascript - jQuery 检查 <li> 是否包含 2 个 img 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50738631/