清除javascript中的未定义值

时间:2013-10-30 18:13:52

标签: javascript

function test()
{
    var testcodevalue = document.getElementById("testcode").value;
    var testcodetext = document.getElementById("testcode").text;    
    if(testcodetext == undefined)
    {
       formObject.testcode.value = "";
       formObject.testcode.text = "";
    }
}

在上面的脚本onload中,我将testcodevalue作为对象,testccodetext作为undefinedtestcode.value我正在设置一个文本框。问题是每次onload我得testcodetextundefined,并且在文本框中设置了相同的值。我该如何清除它?

1 个答案:

答案 0 :(得分:0)

使用typeof检查它是否未定义:

function test()
        {

                var testcodevalue = document.getElementById("testcode").value;
                var testcodetext = document.getElementById("testcode").text;    
                if(typeof testcodetext === "undefined")
                {
                   formObject.testcode.value =  "";
                   formObject.testcode.text =   "";
                 }
        }