用于基于 PHP 变量更改图像的 JavaScript


javascript for changing image based on php variable

<div style="margin-left:5%;width:5%;float:left;margin-right:10%;">
  <img src="./1.png" id="imgstatus"/>
</div>
<div style="width:80%;float:left;">
  <h3>Your transaction was <?php echo $message; ?> ! Your transaction reference number for any furthur communication is <?php echo $cust_ref_no; ?> .</h3>
</div>
</div>

我有这个html。我想要的只是javascript,它将img src <img src="./1.png" /> if $message='succes'并在$message='failed'<img src="./2.png"/>

您可以使用三元运算符来最小化代码长度。

<div style="margin-left:5%;width:5%;float:left;margin-right:10%;">
  <img src="<?php echo ($message == 'success' ? 'success.jpg' : 'failed.jpg'); ?>" id="imgstatus"/>
</div>
<div style="width:80%;float:left;">
  <h3>Your transaction was <?php echo $message; ?> ! Your transaction reference number for any furthur communication is <?php echo $cust_ref_no; ?> .</h3>
</div>
</div>
<div style="margin-left:5%;width:5%;float:left;margin-right:10%;">
  <img src="<?php
  if($message == 'success')
  {
      echo 'success.jpg';
  }
  else
  {
      echo 'failed.jpg';
  }
  ?>" id="imgstatus"/>
</div>
<div style="width:80%;float:left;">
  <h3>Your transaction was <?php echo $message; ?> ! Your transaction reference number for any furthur communication is <?php echo $cust_ref_no; ?> .</h3>
</div>
</div>