gpt4 book ai didi

javascript - JS : Object is not defined

转载 作者:行者123 更新时间:2023-11-28 13:16:31 27 4
gpt4 key购买 nike

我想在 javascript 中创建一个对象来打印输入的数字,但出现此错误。

Déclaration d'objet.html:30

代码:

  <script type="text/javascript">
// <!--
function Init()

{
var test= new Object;
test.affiche= function()
{
var champ=Number(document.getElementById("champSaisie").value);
alert(Number(champ+4));
};
}
</script>
</head>
<body onload="Init()">

<p><label for="champSaisie">Saisissez un nombre&nbsp;: </label><input type="text" id="champSaisie"></p>
<p><input type="submit" onclick="test.affiche()" value="Effectuer le calcul"></p>



</body></html>

最佳答案

您正在创建的变量 test 是您的 Init 函数的本地变量。

当您尝试在 onclick 处理程序中访问 test 时,它会在 global 中查找 test级别,不存在。

我已更新您的代码以改用 addEventListener

function Init() {
var test = {};
test.affiche = function() {
var champ = Number(document.getElementById("champSaisie").value);
alert(Number(champ + 4));
};
document.getElementById("calc").addEventListener("click", test.affiche);
}

Init();
<p>
<label for="champSaisie">Saisissez un nombre&nbsp;:</label>
<input type="text" id="champSaisie">
</p>
<p>
<input id="calc" type="submit" value="Effectuer le calcul">
</p>

关于javascript - JS : Object is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37462454/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com