我无法为我的画廊图像获取模态框

时间:2018-12-05 07:05:21

标签: php jquery html dynamic modal-dialog

我正在用php做一个动态网站。这是我画廊的代码。我不知道出了什么问题。单击我的画廊图像时,我无法看到模式框。有人可以帮我吗?

var modal = document.getElementsByClassName('myModal');
var img = document.getElementsByClassName('myImg');
var modalImg = document.getElementsByClassName("img01");
var captionText = document.getElementsByClassName("caption");
img.onclick = function() {
  modal.style.display = "block";
  modalImg.src = this.src;
  captionText.innerHTML = this.alt;
}
var span = document.getElementsByClassName("close")[0]; // When the user clicks on <span> (x), close the modal span.onclick = function() { modal.style.display = "none"; }
<?php                                       
	require_once("admin/config/connection.php");
	$proname="";
	$query1="select * from products_tb";
	$resource1=mysql_query($query1,$connection);
	$result1="";

	$id="";
	while($record=mysql_fetch_array($resource1))
	{
	     $pid=$record['pid'];
	     $img="uploads/".$record['proimg'];
	     $proname=$record['proname'];
	     $result1.="<div class='col-md-4 col-sm-4 mrgn_less prd'>
	    <img style='width:300px;' id='myImg' class='modal-content'   src='$img' '>
	<div class='myModal modal'>
	  <span class='close'>&times;</span>
	  <img class='modal-content img01' >
	  <div class='caption'></div>
	</div>
						<br>
			 </div>";		  
	}
	?>
<?php  echo $result1;?>

1 个答案:

答案 0 :(得分:0)

如下更新您的JavaScript代码

var modal = document.getElementsByClassName('myModal');
var img = document.getElementsByClassName('myImg');
var modalImg = document.getElementsByClassName("img01");
var captionText = document.getElementsByClassName("caption");
img[0].onclick = function() {
  modal[0].style.display = "block";
  modalImg[0].src = this.src;
  captionText[0].innerHTML = this.alt;
}
var span = document.getElementsByClassName("close")[0];

当您使用“ getElementsByClassName”时,它将返回html元素的对象,因此您需要使用[0]从该对象获取html元素。