函数与onclick一起使用但不能通过javascript工作

时间:2013-01-29 21:48:59

标签: javascript

<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">

为什么函数changeTextonclick="changeText('tare.e')"调用时有效,但在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>

3 个答案:

答案 0 :(得分:0)

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

在JavaScript代码周围添加以下代码......

window.onload = function () {

   changeText('tare.e','from javascript' );

};

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

答案 1 :(得分:0)

您在加载文档之前调用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>

答案 2 :(得分:0)

我发现this关于功能..我仍然对功能感到困惑,希望它可以帮到你