我动态地(通过php)生成了一个视频列表,每个视频都属于一个带有个人资料图片("userpic")的不同用户。我能够将"userpic"传递给在php中调用的javascript函数"video",如第一个echo语句中的如下:
<?php
//Lots of code
echo "<script>
function video(userpic) {
function AnotherFunction();
document.getElementById('UserPicHolder').innerHTML = userpic;
}
</script>";
//Lots of code
?>
函数"视频"调用另一个函数(效果很好)。var = userpic 的路径是正确的本地路径,并在正确的div 中正确显示("UserPicHolder")。一切正常...然后我将内部 HTML 更改为图像属性,如下所示:
<?php
//Lots of code
echo "<script>
function video(userpic) {
function AnotherFunction();
document.getElementById('UserPicHolder').innerHTML = '<img src='"userpic'"
style='"width:50px; height:55px'" alt='"user picture'" class='"SomeClass'"
title='"Some text'">';
}
</script>";
//Lots of code
?>
在第二个 echo 语句中,即使路径明显正确,如第一个 echo 语句所示,图像也不会显示在"UserPicHolder"中。我已经将 src 中的用户图片替换为本地路径,并且图标显示正确(在第三个 echo 语句中):
<?php
//Lots of code
echo "<script>
function video(userpic) {
function AnotherFunction();
document.getElementById('UserPicHolder').innerHTML = '<img src='"images/icon.jpg'"
style='"width:50px; height:55px'" alt='"user picture'" class='"SomeClass'"
title='"Some text'">';
}
</script>";
//Lots of code
?>
为什么第二个回显语句中的用户图片没有在内部HTML img src中被识别?注意我还用src=''".userpic替换了(只是在阅读其他帖子后猜测)src=''"userpic"。''" 和 src=''"+userpic+"''" 和 src=''"+userpic+''" 和 src=''".+userpic+."''"无济于事。 感谢您的任何帮助!
正确的方法是src='"'+userpic+''"
,如:
document.getElementById('UserPicHolder').innerHTML = '<img src='"'+userpic+''" style='"width:50px; height:55px'" alt='"user picture'" class='"SomeClass'" title='"Some text'">';
这是因为userpic
是一个 JS 变量,因此需要与字符串的其余部分连接。 字符串的第一部分是 '<img src='"'
,然后添加变量,然后''" style='"width:50px; height:55px'" alt='"user picture'" class='"SomeClass'" title='"Some text'">'
话虽如此,为什么你回显一长串而不是退出 PHP,就像这样:
<?php
//Lots of code
?>
<script>
function video(userpic) {
function AnotherFunction();
document.getElementById('UserPicHolder').innerHTML = '<img src="'+userpic+'">';
}
</script>
<?php
//Lots of code
?>
您在此处未正确更改innerHTML
:
document.getElementById('UserPicHolder').innerHTML = '<img src='"userpic'"
style='"width:50px; height:55px'" alt='"user picture'" class='"SomeClass'"
title='"Some text'">';
这将使src
= 始终userpic
要动态选择它,请使用串联运算符+
并将代码更改为:
document.getElementById('UserPicHolder').innerHTML = '<img src='"'+userpic+"'"
style='"width:50px; height:55px'" alt='"user picture'" class='"SomeClass'"
title='"Some text'">';