javascript - jQuery 检查 <li> 是否包含 2 个 img 标签

标签 javascript jquery

我想检查单个 li 标签是否包含单个或 2 个 img 标签,并仅在有 2 个 img 时运行 jQuery 脚本> 标签。现在,当单个 li 仅包含一张图像时,它会在单击后消失。

它应该按照以下方式工作:

  1. 加载时 - 显示第一张图片,隐藏第二张图片
  2. 点击时 - 第一张图片隐藏,显示第二张图片
  3. 点击第二张图片 - 第二张图片隐藏,显示第一张图片

$(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/

相关文章:

javascript - 如何使用 Cheerio 获取这些值?

隐藏输入元素的 Javascript 和 defaultValue

c# - javascript 是否等效于 C#s HttpUtility.HtmlEncode?

jquery - Firefox 附加 sdk(如果 AJAX 请求失败)

javascript - JQueryUI/SelectMenu - 底部意外填充

jQuery toggle() 在 Firefox 上工作正常,但在 Chrome 中出现奇怪的现象

javascript - 滚动时更改菜单 css

javascript - 将 HTML DIV 转换为可重用的全局函数?也许是 JavaScript?

javascript - jQuery 自动完成功能,用于为 ajax 调用动态创建输入

jquery - 100% 全屏 Colorbox (jquery lightbox) 滚动条不会替换或覆盖基础层的滚动条