无法将属性'nodeValue'设置为null

时间:2013-04-26 23:35:26

标签: javascript html nodevalue

我正在阅读一本书似乎是对的,但是下面的代码一直给我错误:无法设置null的属性'nodeValue'。代码对我有意义,但我不明白为什么单击清除按钮时无法清除文本值。

var clear = function(){

        $("miles").firstChild.nodeValue = "";
        $("gallons").firstChild.nodeValue = "";
        $("mpg").firstChild.nodeValue = "";
         }

    window.onload = function () {
        $("calculate").onclick = calculateMpg;
        $("miles").focus();
        $("clear").onclick = clear;
    }   

HTML

<section>
    <h1>Calculate Miles Per Gallon</h1>
    <label for="miles">Miles Driven:</label>
    <input type="text" id="miles"><br>
    <label for="gallons">Gallons of Gas Used:</label>
    <input type="text" id="gallons"><br>
    <label for="mpg">Miles Per Gallon</label>
    <input type="text" id="mpg" disabled><br>
    <label>&nbsp;</label>
    <input type="button" id="calculate" value="Calculate MPG"><br>
    <input type="button" id="clear" value="clear"><br>
</section>

3 个答案:

答案 0 :(得分:2)

我认为您想要的是直接在输入字段中使用.value属性的地方:

var clear = function() {
    $("miles").value = "";
    $("gallons").value = "";
    $("mpg").value = "";
 }

以下是对正在发生的事情的解释。现在我们可以看到您的整页并看到$document.getElementById(),问题是您是其中一些节点没有firstChild。

例如,带有id="miles"的对象是输入标记,且没有子级,因此.firstChildnull

在这一行:

$("miles").firstChild.nodeValue = "";

$("miles")获取DOM对象。

$("miles").firstChild返回null,因为该DOM对象没有子项。

$("miles").firstChild.nodeValue = "";是一个错误,因为$("miles").firstChildnullnull没有属性.nodeValue

答案 1 :(得分:1)

输入元素没有子节点,因此firstChild会为您提供null,如果您尝试使用value属性清除输入字段的值,则会更多。

var clear = function(){
    $("miles").value = "";
    $("gallons").value = "";
    $("mpg").value = "";
}

答案 2 :(得分:0)

查看您在评论中发布的代码,问题是$("miles")和其他元素没有任何子元素。

看起来你正试图做这样的事情:

var clear = function() {
    $("miles").value = "";
    $("gallons").value = "";
    $("mpg").value = "";
}
相关问题