1

我需要使用 type="button" 更改输入的值。另一个函数通过将“value”属性与“defaultValue”属性进行比较来检查它的值是否已更改(但这不是重点……)。除了 type="button" 的输入之外,这对其他所有内容都适用。由于某种原因,浏览器也会更改默认值。但为什么?

注意:没有 jQuery!

这是一个简化的测试代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="de" lang="de">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <script type="text/javascript">
            function d(input)
            {
                alert("value: "+ input.value +"\ndefaultValue: "+ input.defaultValue);
            }
        </script>
    </head>
<body>
    <input type="button" value="0" onclick="d(this); this.value=1; d(this);" />
</body>
</html>
4

2 回答 2

0

Put the definition of d directly in the global scope : http://jsfiddle.net/UQTY2/34/

   window.d = function (input) {
       alert("value: " + input.value + "\ndefaultValue: " + input.defaultValue);
   }
于 2013-03-24T18:00:38.687 回答
0

Nice question! It doesn't work with type="reset" too.
That's because they don't have specified data type and they are just buttons.
You can save the first value of the button and then use it. I wrote an example for you:

<!DOCTYPE HTML>
<html>
    <head></head>
    <body>
        <input id="test" type="button" value="Old text" onclick="d(this); this.value='Hello, new text';"/>
        <script type="text/javascript">
            var defaultValueOfInput = document.getElementById("test").value;
            function d(button){
                alert("Value: "+button.value+"\ndefaultValue: "+defaultValueOfInput);
            }
        </script>
    </body>
</html>

EDIT: Updated my code.

于 2013-03-24T18:01:48.180 回答