javascript - 使用 jQuery 中的关联 ID 在单击时切换图像
问题描述
我有一个重复的组件,其中包含一个在显示 2 个图像(移动图像和桌面图像)之间切换的控件。我需要每个控件只切换它所在的组件,并且独立于其他所有组件运行。
我能够为所有控件生成唯一的 ID,为所有图像生成唯一的 ID,并且在单击时我能够添加/删除类以及显示/隐藏图像。我的问题是我不知道如何将切换控件 ID 与图像 ID 相关联,因此我只更改了一个组件。现在我的目标是类(每个组件都相同),所以当你点击控件时一切都会切换。
这是在 Wordpress 中使用 Visual Composer,所以我不相信我能够使用循环来呈现重复的组件。
下面是一个单独的组件,它会被重复多次
<div class="wrapper">
<div class="platform-toggle">
<div class="mobile-toggle">
mobile
</div>
<div class="desktop-toggle">
desktop
</div>
</div>
<div class="platform-images">
<img class="mobile-image" src="https://via.placeholder.com/100x100.png?text=mobile" />
<img class="desktop-image" src="https://via.placeholder.com/100x100.png?text=desktop" />
</div>
</div>
$.each($('.platform-toggle'), function(ind) {
$(this).attr('id', 'platform-toggle_' + parseInt(ind + 1));
});
$.each($('.mobile-toggle'), function(ind) {
$(this).attr('id', 'mobile-toggle_' + parseInt(ind + 1));
});
$.each($('.desktop-toggle'), function(ind) {
$(this).attr('id', 'desktop-toggle_' + parseInt(ind + 1));
});
$.each($('.mobile-image'), function(ind) {
$(this).attr('id', 'mobile-image_' + parseInt(ind + 1));
});
$.each($('.desktop-image'), function(ind) {
$(this).attr('id', 'desktop-image_' + parseInt(ind + 1));
});
$(".mobile-toggle").click(function() {
if ($(".mobile-toggle").hasClass("inactive")) {
$(".mobile-toggle").removeClass("inactive");
$(".mobile-toggle").addClass("active");
$(".mobile-image").show()
$(".desktop-toggle").removeClass("active");
$(".desktop-toggle").addClass("inactive");
$(".desktop-image").hide()
}
});
$(".desktop-toggle").click(function() {
if ($(".desktop-toggle").hasClass("inactive")) {
$(".desktop-toggle").removeClass("inactive");
$(".desktop-toggle").addClass("active");
$(".desktop-image").show()
$(".mobile-toggle").removeClass("active");
$(".mobile-toggle").addClass("inactive");
$(".mobile-image").hide()
}
});
解决方案
这应该与@Slim 的答案完全相同,但使用简化的代码不会一次又一次地重新选择相同的元素。jQuery 中的$()
选择器很快,但如果我们不需要,没有理由继续选择$(this)
7 次。
$(".mobile-toggle").click(function() {
var $this = $(this);
if ($this.hasClass("inactive")) {
$this.removeClass("inactive").addClass("active");
//find current toggle element parent, then find next element(wrapper of the images) and finally find children image.
var $platformImgs = $this.parent('.platform-toggle').next('.platform-images')
$platformImgs.children('.mobile-image').show();
$this.siblings('.desktop-toggle').removeClass("active").addClass("inactive");
$platformImgs.children('.desktop-image').hide();
}
});
推荐阅读
- c# - 如何将 PrivateKeyCiphertextBlob 或 PrivateKeyPlaintext 转换为字符串?
- assembly - “自修改链接”在 Pegasus 编程中是如何工作的?
- react-native - 反应导航 v 2x 将默认参数设置到屏幕中
- ios - 使用打开按钮从试飞中打开应用程序时在启动时崩溃
- matlab - 如何在 MATLAB 中使用点生成圆顶
- amazon-web-services - AWS ECS 容量提供商
- c# - 将参数传递给 C# 中的 .cmd 文件
- spring - Spring @RequestBody 是如何工作的?以及@RequestBody 如何映射 json 来自定义对象?
- javascript - 如果在移动设备中打开菜单,如何停止正文滚动?
- java - Flink 原始和托管状态。什么时候使用它们?