Javascript onclick函数调用传递表单名称而不带引号结果

javascript onclick function call passing form name without quotes results

本文关键字:结果 函数调用 onclick 表单 Javascript      更新时间:2023-09-26
<html>
    <head>
        <script>
            function calledHere(value) { console.log(value); }
        </script>
    </head>
    <body>
        <form name="test">
            <input type="button" value="click!" onclick="calledHere(test);" >
        </form>
    </body>
</html>
从上面的代码中,在onclick调用中错误地传递了没有引号的表单名称。但是,输出显示了整个表单DOM元素。不知道form元素是怎么来的

任何帮助都将对我学习javascript方面更有用。

提前感谢!!

您已经在'value'变量中获得了form元素。您看到元素的html被记录的原因是console.log调用了元素的. tostring()方法。

下面的代码演示了'value'引用了form元素:

<html>
    <head>
        <script>
            function calledHere(value) { value.style.backgroundColor = "red" }
        </script>
    </head>
    <body>
        <form name="test">
            <input type="button" value="click!" onclick="calledHere(test);" >
        </form>
    </body>
</html>
http://jsfiddle.net/John_C/KZ3KR/

这个答案解释了变量的作用域;为什么可以将表单名称传递给函数:https://stackoverflow.com/a/1416157/1588990