基于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-"部分。