将类添加到特定图像的父div

时间:2013-05-17 20:30:31

标签: javascript jquery underscore.js instagram

  (function(){
  var photoTemplate, resource;

  function init(){
    bindEventHandlers();
    photoTemplate = _.template($('#photo-template').html());
  }

  function toTemplate(photo){
    photo = {
      count: photo.likes.count,
      avatar: photo.user.profile_picture,
      photo: photo.images.low_resolution.url,
      url: photo.link
    };

    return photoTemplate(photo);
  }

  function toScreen(photos){
    var photos_html = '';

    $('.paginate a').attr('data-max-tag-id', photos.pagination.next_max_id)
                    .fadeIn();

    $.each(photos.data, function(index, photo){
      photos_html += toTemplate(photo);
    });

    $('div#photos-wrap').append(photos_html);
  }

  function generateResource(tag){
    var config = Instagram.Config, url;

    if(typeof tag === 'undefined'){
      throw new Error("Resource requires a tag. Try searching for cats.");
    } else {
      // Make sure tag is a string, trim any trailing/leading whitespace and take only the first 
      // word, if there are multiple.
      tag = String(tag).trim().split(" ")[0];
    }

    url = config.apiHost + "/v1/tags/" + tag + "/media/recent?callback=?&client_id=" + config.clientID;

    return function(max_id){
      var next_page;
      if(typeof max_id === 'string' && max_id.trim() !== '') {
        next_page = url + "&max_id=" + max_id;
      }
      return next_page || url;
    };
  }


function paginate(max_id){    
        $.getJSON(generateUrl(tag), toScreen);
      }

      function search(tag){
        resource = generateResource(tag);
        $('.paginate a').hide();
        $('#photos-wrap *').remove();
        fetchPhotos();
      }

      function fetchPhotos(max_id){
        $.getJSON(resource(max_id), toScreen);
      }

      function bindEventHandlers(){
        $('body').on('click', '.paginate a.btn', function(){
          var tagID = $(this).attr('data-max-tag-id');
          fetchPhotos(tagID);
          return false;
        });

        // Bind an event handler to the `submit` event on the form
        $('form').on('submit', function(e){

          // Stop the form from fulfilling its destinty.
          e.preventDefault();

          // Extract the value of the search input text field.
          var tag = $('input.search-tag').val().trim();

          // Invoke `search`, passing `tag` (unless tag is an empty string).
          if(tag) {
            search(tag);
          };

        });

      }

      function showPhoto(p){
        $(p).fadeIn();
      }

      // Public API
      Instagram.App = {
        search: search,
        showPhoto: showPhoto,
        init: init
      };
    }());

    $(function(){
      Instagram.App.init();

      // Start with a search on yogofactory; we all love frozen yogurt :).
      Instagram.App.search('yogofactory');  
    });

然后转到HTML文件并围绕此

构建库
<script type="text/template" id="photo-template">
      <div class='photo'>
          <img class='main' src='<%= photo %>' width='250' height='250' style='display:none;' onload='Instagram.App.showPhoto(this);' />
        <img class='avatar' width='40' height='40' src='<%= avatar %>' />
        <span class='heart'><strong><%= count %></strong></span>
      </div>
</script>

我在JS或jQuery方面没有经验。我正在寻找一种方法,将一个类添加到父<div class="photo">,当内部图像为src="http://image.com/onlythisone.jpg"且仅在其图像时。

我有一个画廊,一个从Instagram数据库中动态提取的大型图库,我基本上希望能够隐藏某些不遵循我为促销创建的哈希标记规则的照片。

任何帮助都会很棒!提前谢谢!

2 个答案:

答案 0 :(得分:3)

$(function() {
    $('img[src="http://image.com/onlythisone.jpg"]').parent().addClass('myClass')
});

修改

function toScreen(photos) {
    var photos_html = '';

    $('.paginate a').attr('data-max-tag-id', photos.pagination.next_max_id)
        .fadeIn();

    $.each(photos.data, function (index, photo) {
        photos_html += toTemplate(photo);
    });

    photos_html.find('img[src="http://image.com/onlythisone.jpg"]').remove();

    $('div#photos-wrap').append(photos_html);
}

答案 1 :(得分:0)

这是一个用javascript编写的函数,当使用设置为图像的src值和类名的属性调用时,将搜索所有图像并将指定的类添加到它的父级(如果它尚不存在)。只需在加载任何图像后运行该功能。

function addClassToSpecificImageParent(imageUrl, className) {
    Array.prototype.forEach.call(document.getElementsByTagName("img"), function (element) {
        if (element.src === imageUrl && !element.parentNode.classList.contains(className)) {
            element.parentNode.classList.add(className);
        }
    });
}

addClassToSpecificImageParent("http://image.com/onlythisone.jpg", "someClass");

jsfiddle

更新:根据您现在发布的代码,您将添加对上述功能的调用,如下所示

function toScreen(photos) {
    var photos_html = '';

    $('.paginate a').attr('data-max-tag-id', photos.pagination.next_max_id)
        .fadeIn();

    $.each(photos.data, function (index, photo) {
        photos_html += toTemplate(photo);
    });

    $('div#photos-wrap').append(photos_html);

    addClassToSpecificImageParent("http://image.com/onlythisone.jpg", "someClass");
}

更新:现在您已发布更多详细信息的替代方法是使用Underscore模板

HTML - 下划线模板

<script type="text/template" id="photo-template">
      <div class='photo<%= extraclass %>'>
        <img class='main' src='<%= photo %>' width='250' height='250' style='display:none;' onload='Instagram.App.showPhoto(this);' />
        <img class='avatar' width='40' height='40' src='<%= avatar %>' />
        <span class='heart'><strong><%= count %></strong></span>
      </div>
</script>

的Javascript

function toTemplate(photo) {
    photo = {
        count: photo.likes.count,
        avatar: photo.user.profile_picture,
        photo: photo.images.low_resolution.url,
        url: photo.link,
        extraclass: ""
    };

    if (photo.link === "http://image.com/onlythisone.jpg") {
        photo.extraclass = " someclass";
    }

    return photoTemplate(photo);
}