我已经动态生成(通过 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
?>
函数“视频”调用 AnotherFunction(效果很好)。 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 中的 userpic 替换为本地路径,并且图标显示正确(在第三个 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
?>
为什么第二个 echo 语句中的 userpic 在内部 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
?>
关于javascript - 为什么内部 html 的 src 属性不能识别我动态生成的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19461882/