如果我传递一个参数,则不会调用javascript函数

javascript function is not being called if i pass a argument

本文关键字:调用 函数 javascript 参数 一个 如果      更新时间:2024-05-04

函数setImg()如果用参数调用,但没有传递参数,则函数运行,我做错了什么,请帮助。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Untitled Document</title>
    <script type="text/javascript">
         function setImg(p)
         { 
             window.alert(p);
             document.getElementById('img').innerHTML ="<img src=p width='100' height='105'>";
         }
     </script>
</head>
<body>
    <a href="#" onclick="setImg("images/user-icon.png");">load image</a>
    <div id="img">
    </div>
</body>
</html>

您缺少src的引号,而且您应该分解字符串并添加变量,以防止它将p作为文本读取。

将JS更新为以下内容:

<script type="text/javascript">
     function setImg(p)
     { 
       document.getElementById('img').innerHTML ="<img src='" + p + "' width='100' height='105'>";
     }
 </script>

另外,在HTML中,您需要小心引号:

<a href="#" onclick="setImg('images/user-icon.png');">load image</a>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Untitled Document</title>
    <script type="text/javascript">
         function setImg(p)
         { 
             window.alert(p);
             document.getElementById('img').innerHTML ="<img src=p width='100' height='105'>";
         }
     </script>
</head>
<body>
    <a href="#" onclick="setImg('images/user-icon.png');">load image</a>
    <div id="img">
    </div>
</body>
</html>

好吧,你不小心关闭了html属性,你应该使用'单引号。

报价的小错误

更改

<a href="#" onclick="setImg("images/user-icon.png");">load image</a>

<a href="#" onclick="setImg('images/user-icon.png');">load image</a>