无法将字符串传递给函数

cannot pass string to function

本文关键字:函数 字符串      更新时间:2023-09-26

我正在使用javascript,我尝试将字符串传递给函数,就像这样

        //example string
        var f="a";
//add button that sends the value of f to the function
     document.getElementById("mydiv").innerHTML="<input type='button' id='myButton' value='Click here' onclick='gothere("+f+");'> ";
    function gothere(a){
    alert(a);
    }

我从未看到警报,并且在控制台中我看到a is not defined(指的是我猜的 f?

如果我将 f var设置为数字,则会看到警报。

我错过了什么?

提前致谢

编辑

我在想也许类似

var buttonnode= document.createElement('input');
document.getElementById("mydiv").appendChild(buttonnode);
buttonnode.onclick=gothere(f);

出于同样的原因不会工作吗?

当你的 HTML get 被渲染时,你会得到onclick='gothere(a);',但实际的 a 变量在此上下文中不存在,您希望将 f 的值作为字符串传递,因此您需要使用 onclick='gothere('""+f+"'");' .请注意参数内的额外引号。这将呈现给onclick='gothere("a");'从而传递字符串。

当使用数字时,它可以工作,因为调用onclick='gothere(5);'是有效的,因为变量不能命名为5 ,并且它会传递数字。

实际上,您的代码中没有a。您正在使用变量f来表示a 。因此,使用它将帮助您:

var f="a";
// write the remains of the code as they are..
function gothere(f) {
  alert(f);
}

现在,当您调用该函数时,浏览器中将出现a警报。

此外,尝试将内容包装在双 qoutes 中""让代码理解这是一个字符串而不是字符。

供点击使用

onclick='gothere(" + f + ")'

现在,由您来写入值。也许问题是因为您没有为f编写值。

尝试诊断错误。我相信不会有任何东西。

或者尝试使用属性字段并使用 jQuery 进行更改。

如何修复您的代码?您缺少变量 F 表示的值两边的引号。因此,当解析变量 F 时,函数变为 gothere(a) 。虽然a不是一个定义的变量(但它是一个值),因此存在错误。

试试这个 !

document.getElementById("mydiv").innerHTML="<input type='button' id='myButton' value='Click here' onclick='gothere('""+f+"'");'> ";

修改后的部件onclick='gothere('""+f+"'");'> "

这应该适合您!

函数参数字符串值图像从 JSON 动态。由于item.product_image2是一个 URL 字符串,因此当您在参数内调用 changeImage 时,您需要将其放在引号中。

我的函数在传递参数内单击。

items+='<img src='+item.product_image1+' id="saleDetailDivGetImg">';
items+="<img src="+item.product_image2+"  onclick='changeImage('""+item.product_image2+"'");'>";

我的函数

<script type="text/javascript">
function changeImage(img)
 {
    document.getElementById("saleDetailDivGetImg").src=img;
    alert(img);
}
</script>
  1. 您需要对值参数使用单引号(请参阅@Nis或@CDspace答案)。
  2. 处理动态点击或其他事件的更好方法是事件绑定。例如,请参阅 jQuery 事件绑定。