函数适用于 OnClick,但不能通过 JavaScript 工作

function works with onclick but not working via javascript

本文关键字:JavaScript 工作 但不能 适用于 OnClick 函数      更新时间:2023-09-26
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">

为什么该函数在onclick="changeText('tare.e')"调用时changeText工作,而在 JavaScript 中调用时不起作用

function changeText(idname,newtext)
{
   document.getElementById(idname).value = newtext;
}
changeText('tare.e','from javascript' );
// Calling here causes the error: `Unable to set value of the property 'value': object is null or undefined` 
</script>
<input id="tare.e" value="text" >
<input id="tare.e_button" type="button"  value="BUTTON"  onclick="   changeText('tare.e','from button')"/>
</body>
</html>

你的 JavaScript 在 HTML 完全加载之前运行。

在你的 JavaScript 代码周围放下以下内容...

window.onload = function () {
   changeText('tare.e','from javascript' );
};

这可确保代码在页面加载时运行。

你在文档加载之前调用 changeText()。如果要在文档首次加载时执行该函数,请在 onload 事件中调用它,例如:

<html>
    <head>
    <script type="text/javascript">
    function changeText(idname,newtext) {
       document.getElementById(idname).value = newtext;
    }
    function window_onload()
    {
    changeText('tare.e','from javascript' );
    }
    </script>
    </head>
<body onload='window_onload()'>
<input id="tare.e" value="text" >
<input id="tare.e_button" type="button"  value="BUTTON"  onclick="   changeText('tare.e','from button')"/>
</body>
</html>

我发现了关于函数的这个..我仍然对函数感到困惑,希望它可以帮助您