0

以下内容不会呈现我在 Chrome 或 Firefox 中看到的任何更改:

var field = document.getElementById( 'input-id' ), nodeName;

if ( field !== null ) {
    nodeName = field.nodeName.toLowerCase();

    if( nodeName === 'input' || nodeName === 'textarea' ) {
        field.value = 'hello';
        console.log( field.value );
    }
}

这是目标:

<input id="input-id" name="input-name" type="text" required="required" placeholder="example">

但是控制台在两者中都报告了正确的值。为什么?我正在使用经过验证的 HTML5。该脚本位于结束body标记之前。

4

6 回答 6

1

您正在使用,而不是.编辑您的代码,伙计:

var field = document.getElementById( 'input-id' ).nodeName;
于 2013-01-02T06:04:54.083 回答
1

由于您已经说明了以下内容,因此它可能不是脚本加载问题:

该脚本位于结束正文标记之前。

您必须id在页面上有多个相同的元素。查看您的源代码(在 Firefox 上为Ctrl+U)并搜索input-id。确保页面上只有一个元素具有该 ID。

console.log您还可以通过在其他调用中添加以下行来记录正在更改的元素:

console.log( field );

这应该将整个元素记录到控制台并帮助您进一步调试。

于 2013-01-02T06:34:44.133 回答
0

试试这个

 $(function() {
        var field = document.getElementById( 'input-id' ), nodeName;
        if ( field !== null ) {
            nodeName = field.nodeName.toLowerCase();

            if( nodeName === 'input' || nodeName === 'textarea' ) {
                field.value = 'hello';
                console.log( field.value );
            }
        }
     });

或将您的脚本放在页面末尾。

它不起作用的原因是因为您的脚本在您的输入标签渲染之前执行。所以将它放在 end 或 body load 事件中,或者如果您使用 jquery 而不是放入文档就绪函数

于 2013-01-02T06:12:03.210 回答
0

您的脚本可能在您的输入元素之前加载。

尝试将您的代码段放在页面底部。

于 2013-01-02T06:14:03.247 回答
0

我认为您缺少添加onload function. 你可以添加<body>喜欢

<body onload="sumfunction();">

或在javascript中

<script>
    window.onload = sumfunction; 
</script>

这是一个例子:http: //jsbin.com/ezovun/1/edit

于 2013-01-02T06:24:51.327 回答
0

Turns out I was accidentally overwriting the input value to the empty string elsewhere in the script, immediately after I set it with the code in the OP. My console.log, being in the place that it was, grabbed the value before it was overwritten, which is why it reported the correct value despite getting a different result in the browser. I apologize for not posting the entire script, but I was trying to offer a reduced example.

于 2013-01-03T03:33:15.513 回答