jquery - 如何避免重复大量代码并将相同的规则应用于多个类

标签 jquery

例如,我有 12 个图像,在单击图像时我想隐藏其他 11 个图像并将单击的图像增加到全屏

我正在尝试找出是否有一种更简单、更直接的方法来实现这一点,而不是沿着

编写大量代码
$('.image_one').click(function() {
    $('.image_one').addClass('increase_size');
    $('.image_two').hide(); ...etc for the other 11 images
});

所有图像均为 x 12

我对 jQuery 和 Javascript 的了解还算初级,所以我希望有人能够提出一些建议来简化我想要实现的目标

不要求别人为我写出这段代码,只是为我指明大致方向

最佳答案

您可以使用下面的代码。基本上,当用户单击图像时,所有图像都会被隐藏。然后将显示单击的图像,并将该类添加到其中。

$(document).ready(function() {

  // User clicks on one of the images
  $(".image").click(function() {
    // Hide all the images
    $(".image").hide();

    // Show the image that the user clicks on
    $(this).show();

    // Add the class to the image the user clicks on
    $(this).addClass("increase_size");
  });

});
.increase_size{
    /* your styles */
}

/* Styles to make the image look like box, you won't need this */

img {
  width: 100px;
  height: 100px;
}


/* note, the id's are just to add backgorund to each color, don't need this either. */

#image1 {
  background-color: red;
}

#image2 {
  background-color: green;
}

#image3 {
  background-color: black;
}

#image4 {
  background-color: grey;
}
<!DOCTYPE HTML>
<html>

<head>
  <title>Test Webpage</title>
</head>

<body>
  <img src="image1.jpg" class="image" id="image1">
  <img src="image2.jpg" class="image" id="image2">
  <img src="image3.jpg" class="image" id="image3">
  <img src="image4.jpg" class="image" id="image4">

  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>

</html>
你看……很简单。希望这可以帮助。快乐编码:)

关于jquery - 如何避免重复大量代码并将相同的规则应用于多个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59805812/

相关文章:

javascript - 使用 Jquery 和 Ajax 根据组合框中选定的值自动填充表单

php - 使用 php、js 和 mysql 的导航菜单

jquery - 更改鼠标移动光标类型

javascript - Turbolinks 使页面加载为空白

php - 仅显示具有不同名称的 <h1> 的第一个

jQuery - 多个事件处理程序 - 指定顺序

javascript - jquery 立即加载内容,然后每 10 秒更新一次

jquery - Uploadify 在 IE 7/8 中导致错误

javascript - 在 Javascript 的 for 循环中评估数组的所有值时出现问题

javascript - 将 mouseenter 事件更改为定时事件