无法将参数传递给作为php脚本变量的javascript函数

无法将参数传递给作为php脚本变量的javascript函数,php,Php,我是新来的php,我不知道如何使php和javascript之间的东西,请纠正我,如果我错了 <!doctype html> <html> <head> <Script type="text/javascript"> function show(m) { var k = document.getElementById(m); k.src="four.jpg"; } </head> <body> <? --some

我是新来的php,我不知道如何使php和javascript之间的东西,请纠正我,如果我错了

<!doctype html>
<html>
<head>
<Script type="text/javascript">
function show(m)
{
 var k = document.getElementById(m);
 k.src="four.jpg";
}
</head>
<body>
<? --some php code--
  $i       = 2;
  $row[$i] = "somefilename";
  printf('<img src="%s" id="%d"  onclick="show($i)"/>', $row[$i],$i);
?>
请帮我拿这些。实际上可能吗?据我所知,javascript是浏览器脚本,php是服务器端脚本,我们可以通过这种方式将变量从php传递到javascript吗?

试试这个

printf('<img src="%s" id="%d"  onclick="show('.$i.')"/>', $row[$i],$i);
printf('<img src="%s" id="%d"  onclick="show(this.id)"/>', $row[$i],$i);
printf(“”,$row[$i],$i);

在PHP中,单引号内的所有内容都按原样打印。因此,在您的情况下,应该是:

printf('<img src="%s" id="%d"  onclick="show(' . $i . ')"/>', $row[$i],$i);
printf(“”,$row[$i],$i);

为了使用变量引用,您需要打印带有双引号的字符串:

printf("<img src=\"%s\" id=\"%d\"  onclick=\"show($i)\" />", $row[$i],$i);
printf(“,$row[$i],$i);

我还没有测试过它,但这应该对您有用。

有趣的是,到目前为止,所有回答的人都已将printf参数更改为使用双引号或连接变量。为什么不:

printf('<img src="%s" id="%d"  onclick="show(%d)"/>', $row[$i],$i,$i);
printf(“”,$row[$i],$i,$i);
因为他已经在使用printf()

此外,您实际上不需要PHP中的值,因为它已经存在于HTML中。您只需使用:

printf(“”,$row[$i],$i);


ID不受支持number@MarekSebera但是,当我在html文件中使用onclick=“show('1')”时,它起作用了,但它仍然不起作用valid@niko:可能有效,但不是标准,因此可能有效或无效。。。如果你不想让你的用户更好地与你联系,那么你为什么不把它打印成src和ID?
printf('<img src="%s" id="%d"  onclick="show(%d)"/>', $row[$i],$i,$i);
printf('<img src="%s" id="%d"  onclick="show(this.id)"/>', $row[$i],$i);
<?php

  $i       = 2;
  $row[$i] = "somefilename";
  printf('<img src="%s" id="%d"  onclick="show(' . "'" . %d . "'" . ')"/>', $row[$i],$i);

?>