单击处理程序停止事件传播

Stop event propagation on click handler

我有一个页面包含多个动态生成的列表。这些列表由创建滑块的图像组成,因此您可以单击箭头查看下一张或上一张图像。但是,现在每次单击任何上一个或下一个按钮都会影响页面上的所有列表。我如何修改此代码以停止事件传播并仅影响发生点击的列表?

这是基本的 HTML 结构(它是一个 Prestashop,但它会生成类似这样的东西):

<div class="image-thumbs-container">

  <ul class="thumbnails-custom-list">
    <li> <!-- image --> </li>
    <li> <!-- image --> </li>
  </ul>

  <div class="list-inline-controls">
    <div class="list-left-control"> &#x2329; </div>
    <div class="list-right-control"> &#x232A; </div>
  </div>

</div>


var $first = $('li:first', 'ul.thumbnails-custom-list'),
    $last = $('li:last', 'ul.thumbnails-custom-list');
$(".list-right-control").click(function () {
    var $next, $selected = $(".selected");

    $next = $selected.next('li').length ? $selected.next('li') : $first;
    $selected.removeClass("selected");
    $next.addClass('selected');

});

$(".list-left-control").click(function () {
    var $prev, $selected = $(".selected");

    $prev = $selected.prev('li').length ? $selected.prev('li') : $last;
    $selected.removeClass("selected");
    $prev.addClass('selected');
});

这应该可以解决问题。

现在 "arrows" 只会影响 div class="image-thumbs-container" 内的 li,点击的箭头也存在。

$(".list-right-control").click(function() {
  var $first = $(this).closest(".image-thumbs-container").find('ul.thumbnails-custom-list li:first');

  var $next, $selected = $(this).closest(".image-thumbs-container").find(".selected");

  $next = $selected.next('li').length ? $selected.next('li') : $first;
  $selected.removeClass("selected");
  $next.addClass('selected');

});

$(".list-left-control").click(function() {
  var $last = $(this).closest(".image-thumbs-container").find('ul.thumbnails-custom-list li:last');

  var $prev, $selected = $(this).closest(".image-thumbs-container").find(".selected");

  $prev = $selected.prev('li').length ? $selected.prev('li') : $last;
  $selected.removeClass("selected");
  $prev.addClass('selected');
});
.selected {
  color: yellow
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="image-thumbs-container">

  <ul class="thumbnails-custom-list">
    <li>
      img
    </li>
    <li>
      img
    </li>
  </ul>

  <div class="list-inline-controls">
    <div class="list-left-control"> &#x2329; </div>
    <div class="list-right-control"> &#x232A; </div>
  </div>

</div>


<div class="image-thumbs-container">

  <ul class="thumbnails-custom-list">
    <li>
      img
    </li>
    <li>
      img
    </li>
    <li>
      img
    </li>
    <li>
      img
    </li>
  </ul>

  <div class="list-inline-controls">
    <div class="list-left-control"> &#x2329; </div>
    <div class="list-right-control"> &#x232A; </div>
  </div>

</div>