我正在尝试在我的WordPress主题中创建一个页面,其中帖子显示在CSS网格中。单击网格方块时,所单击帖子的特征图像将显示在模式窗口中。我已经设法使模式窗口工作,但无论选择了哪个帖子,它都会显示最近帖子的特色图像。我尝试使用get_post_id
但我不知道如何将其传递给JavaScriptgetElementById
? (如果这是解决这个问题的正确方法?)
我是一个新手,对JavaScript不太熟悉,如果有任何帮助,我将不胜感激。
这是我的代码:
<?php
/**
* Template Name: Home Page
*/
get_header(); ?>
<div class="grid-container">
<?php
$args = array(
\'post_type\' => \'artists\',
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) :
$the_query->the_post();
?>
<?php $postId = get_the_ID(); ?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<div id="popup">
<img class= "featured-img" id="myImg" src="wp-content/themes/dollarartclub/images/women.png" alt="Snow" style="width:100%;max-width:300px">
</div><!-- modal -->
<div id="mymodal" class="modal">
<span class="close">×</span>
<img class="modal-content" id="img01-<?php echo $postId?>" src="<?php the_post_thumbnail_url($postId); ?>"/>
</div>
</article>
<?php
endwhile;
endif;
wp_reset_query(); ?>
</div>
jQuery(document).ready(function($)
{
var articles = document.querySelectorAll("article");
for (var i = 0; i < articles.length; i++) {
var article = articles[i];
var modal = article.querySelector(".modal");
var button = article.querySelector(".featured-img");
var closeButton = article.querySelector(".close");
// if there is no modal, ignore this article
if (!modal) continue;
button.onclick = function() {
modal.style.display = "block";
}
closeButton.onclick = function() {
modal.style.display = "none";
}
// add event listener instead so it can be added multiple times
window.addEventListener("click", function(event) {
if (event.target === modal) {
modal.style.display = "none";
}
});
}
});
SO网友:SamRob
好的,我通过尝试在线找到的各种代码片段找到了一个似乎有效的解决方案。不确定这是否是解决这个问题的最佳方式,但由于还没有人回答,因此认为发布以下内容可能有用:-)
我将javascript全部取出,并使用cssW3模式。有效的代码是:
<?php
/**
* Template Name: Home Page
*/
get_header(); ?>
<div class="grid-container">
<?php
$args = array(
\'post_type\' => \'artists\',
);
global $post;
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) :
$the_query->the_post();
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<img onclick="document.getElementById(\'mymodal-<?php the_ID(); ?>>\').style.display=\'block\'" class= "featured-img" id="myImg-<?php the_ID(); ?>" src="wp-content/themes/dollarartclub/images/women.png" alt="Snow" style="width:100%;max-width:300px">
<!-- modal -->
<div id="mymodal-<?php the_ID(); ?>>" class="modal">
<span onclick="document.getElementById(\'mymodal-<?php the_ID(); ?>>\').style.display=\'none\'"
class="w3-button w3-display-topright">×</span>
<img class="modal-content" id="img01-<?php the_ID(); ?>" data-id="img01-<?php the_ID();?>" src="<?php the_post_thumbnail_url($post->ID); ?>"/>
</div>
</article>
<?php
endwhile;
endif;
wp_reset_query(); ?>
</div>
css样式需要整理,但功能似乎正常。