javascript - 为什么内部 html 的 src 属性不能识别我动态生成的变量?

标签 javascript php parameter-passing

我已经动态生成(通过 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/

相关文章:

php - 如何使用 jQuery Load 并传递参数将 php 文件加载到 div 中

javascript - 更改多个输入的值

Javascript有没有办法检测已请求页面

php - 基于mysql查询创建多维json

javascript - ajax调用后更新数据属性

python-3.x - 我试图将一个非可变整数参数从一个函数传递给其他定义的函数;我怎么了

c++ - 如何判断参数何时来自硬编码数字?

javascript - HTML 标签显示在 ckeditor 底部

javascript - HTML5 Canvas 文本调整大小、旋转和更改颜色

php - EasyPHP 开发服务器 : database server not starting