提问者:小点点

尝试运行javascript函数时获取对象的null值错误[closed]


这是我第一次在这里发帖,而且我对编码还比较陌生,所以请原谅我的无知。

我正在为我的wordpress模板的一个页面工作,当一个div被点击时,会打开一个模式窗口来显示一个图像。

这是我到目前为止的HTML。

<?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 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">&times;</span>
      <img class="modal-content" id="img01">
     <div id="caption"></div>
    </div>
    
  </article>
       <?php
   endwhile;
endif;
wp_reset_query();
    ?>
  </article>
</div>

Javascript(列在我的functions.php中)

jQuery(document).ready(function($) {
var modal = document.getElementById("myModal");
var img = document.getElementById("myImg");
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function(){
  modal.style.display = "block";
  modalImg.src = this.src;
  captionText.innerHTML = this.alt;
}

var span = document.getElementsByClassName("close")[0];
span.onclick = function() {
  modal.style.display = "none";
}
});

我一直得到控制台错误“uncapted typeerror:can't access property”style“,modal is null”I was gett'can't access onclick,img is null,但是在jquery函数中包装javascript似乎可以阻止这种情况。

一周来我一直在努力让它工作,但没有运气,它快把我逼疯了。 如有任何帮助,我们将不胜感激。 谢谢!


共1个答案

匿名用户

你的选择器不同,一个有大写的M。

<div id="mymodal" class="modal">
document.getElementById("myModal")