停止点击处理程序上的事件传播

时间:2017-08-24 07:55:19

标签: jquery event-propagation

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

这是基本的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');
});

1 个答案:

答案 0 :(得分:1)

这应该可以解决问题。

现在&#34;箭头&#34;只会影响点击箭头所在的li内的div class="image-thumbs-container"

&#13;
&#13;
$(".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');
});
&#13;
.selected {
  color: yellow
}
&#13;
<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>
&#13;
&#13;
&#13;