首页 > 解决方案 > 使用 jQuery 中的关联 ID 在单击时切换图像

问题描述

我有一个重复的组件,其中包含一个在显示 2 个图像(移动图像和桌面图像)之间切换的控件。我需要每个控件只切换它所在的组件,并且独立于其他所有组件运行。

我能够为所有控件生成唯一的 ID,为所有图像生成唯一的 ID,并且在单击时我能够添加/删除类以及显示/隐藏图像。我的问题是我不知道如何将切换控件 ID 与图像 ID 相关联,因此我只更改了一个组件。现在我的目标是类(每个组件都相同),所以当你点击控件时一切都会切换。

这是在 Wordpress 中使用 Visual Composer,所以我不相信我能够使用循环来呈现重复的组件。

JSFiddle 这里

下面是一个单独的组件,它会被重复多次

<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()
  }
});

标签: javascriptjquerywordpress

解决方案


这应该与@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();
  }
});

推荐阅读