简体   繁体   中英

javascript function is not being called if i pass a argument

the function setImg() if called with an argument is not running but if no argument is passed then the function runs what mi doing wrong please help.

<!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>

You are missing the quotes for the src plus you should break up the string and add the variable to prevent it reading p as text.

Update the JS to the following:

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

Plus in the HTML you need to be careful with quotes:

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

Small mistake of quotes

change

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

to

<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>

Well your were closing html attribute accidentally, you should use ' single-quotes instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM