scenario

TypeError: Translate is not a function Uncaught TypeError: translate is not a function The code is as follows:

<! DOCTYPEhtml>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Test</title>
</head>
<body>
    <div class="target" onclick="translate()">Click on the</div>
    <script>
      function translate() {
          console.log('translate');
      }
  </script>
  </body>
</html>
Copy the code

Translate is not a function

Troubleshoot problems

  1. Translate1 (translate1) now runs properly after the translate function name is changed to translate1.

  2. In

  3. Combining Uncaught TypeError: Translate is not a function when the div tag onclick is executed. Translate is not an external definition of the translate function. And this definition is a property, not a function.

  4. So I looked up the HTML attribute document of MDN developer.mozilla.org/en-US/docs/… ;

  5. Translate is used to specify whether the attribute value of the corresponding element and its subtext node contents are translated according to the system language.

  6. So when JS executes, translate refers to the translate attribute of the element, hence throwing the above error.

Conclusion:

  1. Avoid registering event handlers directly on HTML tags<script>Script processing

document.getElementByClassName('target').onclick=translate or document.querySelector('.target').addEventListener('click',translate)

  1. Avoid the use oftranslateAs a function name aside, it’s easy to think of another solution that passeswindow.translateCall a function:<div onclick="window.translate()">

3. Similar error-prone attribute names: Tag download attribute……