javascript - 如何使用 jQuery 触发同一容器内的元素

标签 javascript jquery html css

我正在尝试创建一个动态生成以下代码的站点。它有多个 div.container 及其子实例。问题是,当我单击缩略图 (.color-thumbs img) 时,它还会触发所有图像 (.imgWrapper img) 的更改。我需要做的是为缩略图创建一个唯一的触发器,它只会影响同一容器内的图像。

这是我的代码:

$('.color-thumbs img').click(function() {
  var thmb = this;
  var src = this.src;
  $('.color-thumbs img').parent('.imgWrapper').append('crayz');

  $('.imgWrapper img').fadeOut(400,function(){
      thmb.src = this.src;
      $(this).fadeIn(400)[0].src = src;
  });
});
.color-thumbs img{
  margin-right:3px;
  margin-top:3px;
  width:30px;
  height: 30px;
  float:left;

  box-sizing: border-box;
}

.container {
  clear: both;
  margin-bottom: 4em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="container">
  <div class="imgWrapper">
    <img src="http://placehold.it/300x160/cf5" />
  </div>

  <div class="color-thumbs">
    <img src="http://placehold.it/300x160/444" />
    <img src="http://placehold.it/300x160/f1f" />
  </div>
</div>

<div class="container">
  <div class="imgWrapper">
    <img src="http://placehold.it/300x160/cf5" />
  </div>

  <div class="color-thumbs">
    <img src="http://placehold.it/300x160/444" />
    <img src="http://placehold.it/300x160/f1f" />
  </div>
</div>

提前致谢!

最佳答案

您可以使用 .closest()细化被点击的 img 所属的 container 元素,然后使用 .find() 在其中查找目标 .imgWrapper img 元素,例如

$('.color-thumbs img').click(function() {
  var thmb = this;
  var src = this.src;

  $(this).closest('.container').find('.imgWrapper img').stop().fadeOut(400, function() {
    $(this).fadeIn(400)[0].src = src;
  });
});
.color-thumbs img {
  margin-right: 3px;
  margin-top: 3px;
  width: 30px;
  height: 30px;
  float: left;
  box-sizing: border-box;
}
.container {
  clear: both;
  margin-bottom: 4em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="container">
  <div class="imgWrapper">
    <img src="http://placehold.it/300x160/cf5" />
  </div>

  <div class="color-thumbs">
    <img src="http://placehold.it/300x160/444" />
    <img src="http://placehold.it/300x160/f1f" />
  </div>
</div>

<div class="container">
  <div class="imgWrapper">
    <img src="http://placehold.it/300x160/cf5" />
  </div>

  <div class="color-thumbs">
    <img src="http://placehold.it/300x160/444" />
    <img src="http://placehold.it/300x160/f1f" />
  </div>
</div>

关于javascript - 如何使用 jQuery 触发同一容器内的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31397331/

相关文章:

javascript - 为什么 dom 事件在 angularjs 的 Controller 内部不起作用

javascript - 关闭 Materialise CSS Modal 后, "modal-overlay"仍然存在——我们如何在不接触覆盖层的情况下关闭它?

javascript - 不一致的 RegEx 空白清理

html - 在 Dart 中解析 JSON 的最佳方式

javascript - Bootstrap 4 - 附加侧边栏时无法保持相同的宽度

javascript - 如何使用 2 个音频播放器并在另一个播放器播放时停止

javascript - ActiveXObject ("WScript.Shell");在 Firefox 中未定义?

jquery - Twitter Bootstrap 模态表单提交

javascript - Javascript 中函数流的最佳实践?

javascript - 如何在 ExpressJS 中的 HTML 表单上添加值