【发布时间】:2020-07-10 12:06:45
【问题描述】:
所以我想知道如何为循环创建的每个模型设置唯一标识符
我正在循环访问自定义帖子类型,以根据存在的每个帖子创建内容。我想在阅读更多内容时弹出模态,而不仅仅是摘录,而是在循环中。我不确定如何使每个模态标识符唯一,然后在 Javascript 中读取它。
这是循环:
<div class="row">
<?php
$review = new WP_Query(array('post_type' => 'review', 'posts_per_page'=>'-1', 'order_by' => 'post_date', 'order' => 'DSD'));
if($review->have_posts()) : while ($review->have_posts()) : $review->the_post();
?>
<div class="col-lg-3 monial-block mg-top-m">
<div class="flex-r">
<?php
$rating = get_post_meta(get_the_ID(), "wpcf_stars", true);
for ($x = 0; $x < $rating; $x++) :
?>
<span class="fa fa-star checked"></span>
<?php endfor; ?>
<i class="fa fa-bookmark" aria-hidden="true"></i>
</div>
<p>
<?php the_excerpt() ?>
</p>
<button id="myBtn">Read More</button>
<div class="flex-r names">
<hr class="test-hr">
<h4 class="test-name">
<?php the_title() ?>
</h4>
</div>
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<?php the_title() ?>
<?php the_content(); ?>
</div>
</div>
</div>
<?php endwhile; ?>
<?php else : ?>
<p><?php __('No Reviews'); ?></p>
<?php endif; ?>
</div>
</div>
这是 JavaScript
var modal = document.getElementById("myModal");
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
这是 CSS
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content/Box */
.modal-content {
background-color: #fefefe;
margin: 15% auto; /* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 80%; /* Could be more or less, depending on screen size */
}
/* The Close Button */
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
也许我什至不需要唯一标识符,但我很确定这是问题所在。第一个元素是唯一具有工作模型的元素,其余元素已填充内容,但当我单击它们时不会弹出。
【问题讨论】:
-
给他们唯一的 ID 而不是“myBtn”。如果它在循环中,请尝试给出“myBtn-0”、“myBtn-1”等。然后通过以相同方式按 ID 选择元素来循环应用点击侦听器。或者您可以通过添加 JS 来直接将点击监听器添加到您的 PHP 中的按钮。
-
你介意为我发布一个示例 Shyam 吗?
-
可能类似于
var date = new Date(); element.id = "btn-" + date.getTime()
标签: javascript php html jquery css