隐藏基于数据属性的元素 JQuery

Hide Elements based on Data atributte JQuery

我正在尝试编写一个基本的 PHP 脚本,该脚本将获取我自己的 Instagram 照片,并仅根据我添加的主题标签显示我想要的照片。

到目前为止,根据一些教程和我自学的 PHP 和 JS,我想到了这个:

<html>
<head>
        <script src="assets/js/jquery.min.js"></script>
</head>
<?php

    <html>
    <head>
            <script src="assets/js/jquery.min.js"></script>
    </head>
    <?php

      function fetchData($url){
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
      function fetchData($url){
      function fetchData($url){
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_TIMEOUT, 20);
      $result = curl_exec($ch);
      curl_close($ch);
      return $result;
      }

      $result = fetchData("https://api.instagram.com/v1/users/1013397/media/recent/?access_token=1013397.ab103e5.5061b21c8fb0436bb20d881d46f9ae5c&count=14");


      $result = json_decode($result);
      foreach ($result->data as $post) {
         if(empty($post->caption->text)) {
           // Do Nothing
         }
         else {
            echo '
            <div data-tag="'.$post->caption->text.'">
                    <a class="instagram-unit" target="blank" href="'.$post->link.'">
                            <img data-tag="'.$post->caption->text.'" class="gallery-item" src="'.$post->images->standard_resolution->url.'" alt="'.$post->caption->text.'" width="100%" height="auto" />
                    </a>
            </div>';
         }

      }
    ?>
    <script>
    $(document).ready(function(){
            var permit = '#aruba'
            $('div').each(function(){
            if($('div').attr('data-tag').indexOf(permit) > -1 ){
                    console.log('has tag')
            }
            });
    });
    </script>

我试图隐藏所有没有在 JS 栏中写入主题标签的图像。但到目前为止还没有运气。

我做错了什么?

$(document).ready(function(){
    //find all divs, filter out any who do have the matching tag, hide all that don't
    $('div').filter(function(){ return $(this).data('tag') !== "#aruba"; }).hide();
});

关于您的原始问题,您的部分问题是您对 div 执行了 each(),但随后又在内部再次查找它们,因此您失去了实际评估的上下文已通过 'this' 或“$(this)”访问。

此外,在处理数据元素时,请使用 data() 并省略密钥的 'data-' 部分。