[英]Toggle button to show/hide data from API
我的网站上有一个meetup.com API,可以提供事件描述。 我希望通过切换按钮隐藏此信息,以便当您单击“更多信息”时,说明会显示。
这是我的切换按钮的javascript:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").toggle();
});
});
</script>
这是PHP:
$ct = 1;
foreach ($my_array['results'] as $event) {
echo '<strong> ' . $event['name'] . '</strong>' . '<br />';
echo '<strong>Event link: </strong><a href="' . $event['event_url'] .'" target="_blank">' . $event['event_url'] . '</a><br />';
echo '<strong>When: </strong>' . date('Y-m-d H:i', $event['time']/1000) . '<br />' ;
// echo '<strong>More Info: </strong>' . $event['description'] . '<br />';
echo '<strong><button>More Info</button></strong><infobox>' . $event['description'] . '</infobox><br />';
$ct = $ct+1;
这就像现场一样: http : //maddusability.com/icm505/meetups.php
正如您所看到的,它只允许我一次显示/隐藏所有事件描述,而不是单独显示 - 即使我为每个事件创建了一个唯一的ID。 有任何想法吗?
您必须使用this
关键字和DOM遍历来定位正确的元素
$(document).ready(function(){
$("button").click(function(){
$(this).closest('strong').next('infobox').find("p").toggle();
});
});
仅供参考: <infobox>
对我来说似乎是无效的标签?
因为你有一个非常通用的jQuery选择。 您正在切换页面中的所有P标签 。
你应该做的是将每个项目包装在一个具有特定css类的单独div中。 更新php文件,以便生成以下标记
<div class="item">
<strong>Event 1</strong>
<button class="showMore">Show more</button>
<div class="moreInfo">
<p>Your more info description goes here</p>
</div>
</div>
<div class="item">
<strong>Event 2</strong>
<button class="showMore">Show more</button>
<div class="moreInfo">
<p>Your more info about event 2 description goes here</p>
</div>
</div>
现在在你的脚本中,使用showMore
css类查找按钮上的click事件,当它被单击时,使用showMore
closest()
方法获取容器div,然后使用find
方法获取具有内容的div切换。
$(document).ready(function(){
$(".moreInfo").hide(); //Hide all show more initially
$("button.showMore").click(function(){
var _this=$(this);
_this.closest(".item").find(".moreInfo").toggle();
});
});
这是一个工作样本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.