【问题标题】:Deleting divs inside a row with certain condition在具有特定条件的行内删除 div
【发布时间】:2018-02-16 21:36:50
【问题描述】:

我有这个基本的搜索系统,其中包含“卡片”中的文章,如 here 有些文章包含图片,有些则没有。

我只想在“图片框”div 中显示图片时,instead of having a blank white space when there's no picture. 如何只删除没有图片的“图片框”div?

PHP:

$sql = "SELECT * FROM article ORDER BY a_id DESC LIMIT 3";
        $result = mysqli_query($conn, $sql);
        $queryResults = mysqli_num_rows($result);

        if ($queryResults > 0) {
            while ($row = mysqli_fetch_assoc($result)) {

        echo "<a href='article.php?title=".$row['a_title']."&date=".$row['a_date']."'>
               <div class='article-wrapper'>

                    <div class='picture-box'>
                     <img src='".$row['picture']."' class='picture'>
                    </div>

                    <p class='text'>".$row['text']."</p>

                 </div>
              </a>";
            }
          }

CSS:

.picture {
    position:absolute;
    left: -100%;
    right: -100%;
    top: -100%;
    bottom: -100%;
    margin: auto;
    max-width: 100%;
    height: auto;
}

.picture-box {
    width: 560px;
    height: 300px;
    overflow: hidden;
    position: relative;
}

我试过这个:

PHP:

&lt;img src='".$row['picture']."' class='picture' onerror="imgError(this)"&gt;

jquery:

function imgError(img) {
    img.error="";
    $(img).parent().remove();
}

-但它会从所有文章中删除“图片框”div,而不是特定文章。

【问题讨论】:

  • 我认为按照您的做法,最好从服务器端删除。而且 $('img') 应该是 $(img)

标签: php jquery css mysqli


【解决方案1】:

为什么还要首先创建 div 并依赖 jQuery 来清理混乱?最初创建页面时只需在您的PHP中添加一条if语句,如果没有价值,请不要添加图片。

echo "<a href='article.php?title=".$row['a_title']." date=".$row['a_date']."'>
           <div class='article-wrapper'>";

                if(trim($row['picture']) != ''){
                    echo "<div class='picture-box'>
                        <img src='".$row['picture']."' class='picture'>
                    </div>";
                }

                echo "<p class='text'>".$row['text']."</p>

             </div>
          </a>";

【讨论】:

  • 在 while 语句下面添加了这个,它删除了整张缺少图片的卡片,而不仅仅是 div,我做错了吗?
  • 是的,您是否尝试将 if 语句放入 echo 中?那是无效的PHP。所以你需要关闭 echo 并且基本上有三个单独的 echo 语句。我会用完整的解决方案更新我的答案。
【解决方案2】:

应该是$(img).parent().remove();

【讨论】:

    猜你喜欢
    • 2021-08-17
    • 2021-04-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-30
    • 1970-01-01
    • 2020-04-12
    • 2022-11-29
    • 1970-01-01
    相关资源
    最近更新 更多