0

我已经(通过 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
?>

第二个回显语句中,即使路径明显正确,如第一个回显语句所示,图像也不会显示在“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+."\" 无济于事。谢谢你的帮助!

4

2 回答 2

2

正确的方法是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
?>
于 2013-10-19T03:09:48.630 回答
0

您没有正确更改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\">';
于 2013-10-19T03:14:36.400 回答