如何指定$('a')。click事件以仅选择特定的<a>标记,而不选择所有<a>标记?

时间:2019-11-29 16:47:28

标签: jquery html dom-events

我添加了photoswipe插件,该插件使用<a>标签搜索我的所有照片,如果单击,它将把照片变成全屏。我可以使用它,但是现在我的导航栏(带有<a>标签)在单击时触发了photowipe插件。

在photoswipe click事件中,我尝试执行$("a[href*='photo']").click(function(event),以便只有在a的{​​{1}}包含单词href的情况下才会触发click事件-这并没有解决不了。

Photoswipe插件:

photo

照片HTML:

<script>
    'use strict';

    /* global jQuery, PhotoSwipe, PhotoSwipeUI_Default, console */

    (function($){

      // Init empty gallery array
      var container = [];

      // Loop over gallery items and push it to the array
      $('#gallery').find('div.item').each(function(){
        var $link = $(this).find('a'),
            item = {
              src: $link.attr('href'),
              w: $link.data('width'),
              h: $link.data('height'),
              title: $link.data('caption')
            };
        container.push(item);
      });

      // Define click event on gallery item
      $("a").click(function(event){

        // Prevent location change
        event.preventDefault();

        // Define object and gallery options
        var $pswp = $('.pswp')[0],
            options = {
              index: $(this).parent('div.item').index(),
              bgOpacity: 0.85,
              showHideOpacity: true
            };

        // Initialize PhotoSwipe
        var gallery = new PhotoSwipe($pswp, PhotoSwipeUI_Default, container, options);
        gallery.init();
      });

    }(jQuery));
  </script>

我的导航栏:

<div id="gallery" class="gallery grid" itemscope itemtype="http://schema.org/ImageGallery">
  <div class="item" data-color="photography" itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
            <a href="photo/IMG_2322.JPG" data-caption="This is a caption" data-width="1200" data-height="900" itemprop="contentUrl">
              <img class="crop lazy" data-src="photo/IMG_2322.JPG" itemprop="thumbnail" alt="Image description">
            </a> 
   </div>
</div>

2 个答案:

答案 0 :(得分:2)

class="a-photos"添加到所有照片中,而不是使用“ a”标签,并按类别触发可能会解决您的问题。

答案 1 :(得分:1)

$(".a-photos").click(function(event){
    // Prevent location change
    event.preventDefault();
    // Define object and gallery options
    var $pswp = $('.pswp')[0],
        options = {
          index: $(this).parent('div.item').index(),
          bgOpacity: 0.85,
          showHideOpacity: true
        };
    // Initialize PhotoSwipe
    var gallery = new PhotoSwipe($pswp, PhotoSwipeUI_Default, container, options);
    gallery.init();
  });