如何获取点击图像的名称并将其与php变量进行比较?

Two images, placed by php:

echo "<img onclick='test()' src=\"/img/Sun.png."\">";
echo "<img onclick='test()' src=\"/img/Moon.png."\">";
$x = "Sun.png";

js:

function test(){
if (clicked_image_name == $x) ...do something

So, how to get the name of clicked image, and how to compare it with a php variable ?

Put the value of $x in a hidden field. You'd be able to take the value then from javascript

echo "<img onclick='test(this.src)' src=\"/img/Sun.png."\">";
echo "<img onclick='test(this.src)' src=\"/img/Moon.png."\">";

js:

function test(img_src){
var clicked_image_name = img_src.substring(5);
if (clicked_image_name == '<?php echo $x;?>') ...do something

above code snippets will do your job.
thanks

You can do one thing,

You can declare one javascript variable and its value by php code :-

var imageName = "<?php echo "Sun.png"?>";

and you can modify the php code to pass image src name as variable:

echo "<img onclick='test("Sun.png")' src=\"/img/Sun.png."\">";

And then in javscription test() function, you can check its value

function test(imageSrcName)
{
   if(imageSrcName == imageName)
   {
       alert("both image name are same");
   }
   else
   {
       alert("both image name are different");
   }
}

You could simply add an argument to the test() call to your php page like the following:

echo "<img onclick='test(\"$mysunvariable\")'  src=\"/img/Sun.png."\">";
echo "<img onclick='test(\"$mymoonvariable\")' src=\"/img/Moon.png."\">";

And in your JS:

function test(name){
   if(name == 'Sun.jpg'){
      do something
   }
   other cases..
}

Alternatively, if you really need to compare with PHP dynamic variables, you should write a PHP service and call it by an async GET or POST (for example using AJAX).

In that case to get the image name you can add the name parameter to each of your images in your PHP page like this:

echo "<img onclick='test(this)' name=\"sun\"  src=\"/img/Sun.png."\">";
echo "<img onclick='test(this)' name=\"moon\" src=\"/img/Moon.png."\">";

And then modify your JS function as below:

function test(img){
   var myname = img.name;
   here you do your async stuff
...
}