如果我传递一个参数,则不会调用javascript函数
javascript function is not being called if i pass a argument
函数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>
相关文章:
- 如何从模块链中调用函数.导出到节点中
- 调用函数内部的函数
- 在javascript中调用c函数
- DropDownListFor赢得't在更改时调用函数
- Javascript页面调用函数
- 在动画结束之前调用函数
- 允许父窗口在其不同域的子iframe上调用函数
- 运行Infinite Scroll后调用函数时出现问题
- JavaScript:在调用函数的文本输入上按enter键
- 使用大括号和不使用bracs调用函数的区别
- javascript在事件上调用函数
- 从index.html调用函数,该函数无限循环
- 从带参数的字符串变量调用函数中的函数
- 为什么 JS 不在滚动时调用函数
- 是否可以在不更改上下文的情况下调用函数.apply
- 如何在ES6类中使用参数调用函数
- AngularJS:调用函数时编号不更新
- JavaScript中的立即调用函数表达式(IIFE)-传递jQuery
- 在JavaScript中调用函数时自定义此选项
- 调用函数中声明的变量