javascript - 使用 hide/show - on element 当时

标签 javascript php jquery html css

我正在使用 php 和 jquery 在我的网页上打印文章。我希望当时能够在一篇文章上使用显示/隐藏 jquery。就像现在一样,当我按下隐藏或显示所有 <article> 时我的 foreach 循环中的元素受到影响。

HTML 和 PHP 代码

<section class='col-md-8'> <!-- Div for content, images etc. -->


<?php

$page = new CMS();
$gp = $page->getPage();


 foreach ($gp as $sp) {
  //var_dump($sp);

  echo "<div id='pub'>";
  echo "<h4>" . $sp['title'] . "</h4>"; 
  echo "<article id='pub_art'>" . $sp['content'] . "</article>";  
  echo "<p>" . $sp['created'] . "</p>"; 
  echo "<p>". $sp['writer'] ."</p>";
  echo "<button id='hide'>Hide</button>";
  echo "<button id='show'>Show</button>";
  echo "</div>";

}
?>

</section>

J查询代码

$(document).ready(function(){
    $("#hide").click(function(){
        $("article").hide();
    });
        $("#show").click(function(){
            $("article").show();
        });
 });

CSS

  #pub_art {
  width: 100%;
  height: 100%;
  background-color: blue;
  display: none;

 }

最佳答案

因此,首先,您多次使用同一个 ID,将它们更改为类(因为 ID 只能使用一次,而类可以多次使用)。像这样:

$output = '';
foreach($gp as $sp){
    $output .= "<div class='pub'>";
        $output .= "<h4>" . $sp['title'] . "</h4>"; 
        $output .= "<article class='pub_art'>" . $sp['content'] . "</article>";  
        $output .= "<p>" . $sp['created'] . "</p>"; 
        $output .= "<p>". $sp['writer'] ."</p>";
        $output .= "<button class='hide'>Hide</button>";
        $output .= "<button class='show'>Show</button>";
    $output .= "</div>";
}
echo $output;

如您所见,我已将每个 echo 连接到一个变量中并一次 echo ,这是一种更好的方法(性能方面)

现在对于 javascript,您要选择每个 article 标签,而不是这个我们要寻找同级 article ,它位于与hideshow 类。

$(document).ready(function(){
    $(".hide").click(function(){
        $(this).siblings('article').hide();
    });

    $(".show").click(function(){
        $(this).siblings('article').show();
    });
});

还有你的 CSS(现在还有类选择器)

.pub_art {
    width: 100%;
    height: 100%;
    background-color: blue;
    display: none;
}

关于javascript - 使用 hide/show - on element 当时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35767644/

相关文章:

javascript - 如何将光标位置放在 contenteditable 元素的居中对齐占位符的开头?

javascript - 添加超时以 promise 挂起

PHP 奇怪的未定义索引错误

php - 无法在 MySQL-PHP 中的数据库列日期时间类型中存储值

c# - 忽略 Jquery AJAX 调用 URL 的大小写敏感性

javascript - 消息传递在 Chrome 扩展中不起作用

javascript - 简单的语句应该被 Bluebird Promise 中的 Promise.try 包围吗?

javascript - 如何从 JavaScript 更新 UpdatePanel

php - Joomla 如何在提交表单时路由到 Controller 方法?

jquery - 在同一页面上使用不同版本的 jQuery