admin管理员组

文章数量:1425708

Can someone explain me why a function called "action" creates a type error in the following code as soon as the button is surrounded by the form tags. I assume this leads to a strange conflict with the form's action attribute, but i wonder why it happens in this scope ("action" is not defined in any other way):

<html>
<head>
    <script type="text/javascript">
        function action() {
            alert('test');
        }
    </script>
</head>
<body>
    <form>
        <input type="button" value="click" onClick="action();">
    </form>
</body>
</html>

Can someone explain me why a function called "action" creates a type error in the following code as soon as the button is surrounded by the form tags. I assume this leads to a strange conflict with the form's action attribute, but i wonder why it happens in this scope ("action" is not defined in any other way):

<html>
<head>
    <script type="text/javascript">
        function action() {
            alert('test');
        }
    </script>
</head>
<body>
    <form>
        <input type="button" value="click" onClick="action();">
    </form>
</body>
</html>
Share Improve this question asked Jun 2, 2016 at 11:16 needfulthingneedfulthing 1,09612 silver badges22 bronze badges 3
  • 1 I am surprised there is no duplicate for this question – Rayon Commented Jun 2, 2016 at 11:20
  • That's the way inline event handlers work. See my answer here: stackoverflow./questions/6941483/onclick-vs-event-handler/… – Felix Kling Commented Jun 2, 2016 at 13:37
  • @Rayon: this has been asked before, but I can imagine that it is difficult to name the question or what to look for without knowing what the issue is. I mean, the title of this question is not very indicative of the problem. – Felix Kling Commented Jun 2, 2016 at 13:42
Add a ment  | 

1 Answer 1

Reset to default 5

Inside the form, action is a string reference to the form action. If you change your onclick to alert(action) you will get the action of the form (which will be an empty string for your specific form).

In the same manner, form will be a reference to a form, and method will contain the form method, if you use them within the form. window.action will still refer to your function.

本文标签: JavaScript function called quotactionquotStack Overflow