我正在使用 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
,它位于与hide
或 show
类。
$(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/