【问题标题】:Javascript function not getting parsed by HTML fileJavascript函数没有被HTML文件解析
【发布时间】:2021-05-31 08:33:52
【问题描述】:

我有一个问题:

当我单击 HTML 按钮时,没有调用我的 AddCenter() 函数。

编辑:
感谢所有答案,但它仍然无法正常工作。所以这是我所做的更改:
我将代码移动到一个单独的 javascript 文件,但它仍然没有执行。
它应该检查用户输入的一些值,然后将我的 url 从 www.mywebsite.example/api/v1/im 更改为 www.mywebsite.example/
但它会从 www.mywebsite.example/api/v1/im 更改为 www.mywebsite.example/api/v1/im?
HTML 文件:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link
      rel="stylesheet",
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css",
      integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T",
      crossorigin="anonymous"
    />
    <title>World Sport Center - Add Center</title>
    <style>
      .disable-select {
        user-select: none;
        -webkit-user-select: none;
        -khtml-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
      }
    </style>
  </head>

  <body>
    <div class="text-center">
      <div class="container my-3">
        <h1 class="display-4 text-center disable-select">Add Informative Marker</h1>
        <form id="center-form" class="mb-4">
          <div class="form-group">
            <blockquote class="blockquote">
              <p class="mb-0 disable-select">Sport Center Name</p>
            </blockquote>
            <input type="text" id="center-name" class="form-control" />
          </div>
          <div class="form-group">
            <blockquote class="blockquote">
              <p class="mb-0 disable-select">Sport Center Address</p>
            </blockquote>
            <input type="text" id="center-address" class="form-control" />
          </div>
          <div class="form-group">
            <blockquote class="blockquote">
              <p class="mb-0 disable-select">Sport Center Description</p>
            </blockquote>
            <textarea type="text" rows="2" id="center-description" class="form-control" maxlength="150"></textarea>
          </div>
          <div class="form-group">
            <blockquote class="blockquote">
              <p class="mb-0 disable-select">Developper Key</p>
            </blockquote>
            <input type="text" id="dev-key" class="form-control" />
          </div>
          <a href="/api/v1/add" class="btn btn-outline-primary btn-lg"><-- Back</a>
          <button onclick="AddCenter" class="btn btn-lg btn-primary">Submit --></button>
        </form>
      </div>
    </div>
    <script src="/js/informative.js"></script>
  </body>
</html>

Javascript 文件:
const centers = require('../../models/Center');
const centerName = document.getElementById('center-name');
const centerAddress = document.getElementById('center-address');
const centerDescription = document.getElementById('center-description');
const key = document.getElementById('dev-key');

function CheckForURL(str)
{
  let reg = new RegExp('([a-zA-Z\d]+://)?((\w+:\w+@)?([a-zA-Z\d.-]+\.[A-Za-z]{2,4})(:\d+)?(/.*)?)', 'i')
  return reg.test(str)
}

async function AddCenter(e)
{
  e.preventDefault();

  if (centerName.value === '') return alert('Please fill in the "Sport Center Name" field');
  else if (centerAddress.value === '') return alert('Please fill in the "Sport Center Address" field');
  else if (centerDescription.value === '') return alert('Please fill in the "Sport Center Description" field');
  else if (key.value === '') return alert('Please fill in the "Developper Key" field');
  else if (CheckForURL(centerDescription.value)) return alert('You can not put a url in the free marker "Sport Center Description" field');
  else if (key.value !== process.env['DEVELOPER_KEY'])
  {
    alert('You filled in the wrong KEY in the "Sport Center Description" field, and this window will self destruct in 10 seconds');
    var timer = setInterval(function() { 
      window.close();
    }, 10000);
    return;
  }

  centers.create({
    type: 'informative',
    name: centerName.value,
    address: centerAddress.value,
    description: centerDescription.value
  });

  if (res.status === 400)
  {
    throw Error('That sport center already exists !');
  }

  alert('Center added !');
  window.location.href = '/';
}
```<br><br>
I also made all the changes you guys told me to but the javascript function is still not getting called and functioning.

【问题讨论】:

  • 你的问题是AddCenter末尾多余的),如果你在分配按钮点击处理程序时也删除了(),它变成onclick="AddCenter"那么它会通过事件正确。我刚刚测试过,它工作正常。尝试删除错字并检查开发者控制台是否有其他错误。

标签: javascript html node.js function


【解决方案1】:

当页面加载时,您的变量将被设置为空。当AddCenter(e) 被调用时,它正在检索由您的变量设置的那些空值。尝试将它们移动到函数中

  async function AddCenter(e)
  {
    let centers = require('../models/Center');
    let centerName = document.getElementById('center-name');
    let centerAddress = document.getElementById('center-address');
    let centerDescription = document.getElementById('center-description');
    let key = document.getElementById('dev-key');
    e.preventDefault();

【讨论】:

  • 我猜这个例外是...... let centers = require('../models/Center');
【解决方案2】:

我认为你错误地在 AddCenter() 方法的末尾添加了一个右括号')'。

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link
      rel="stylesheet",
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css",
      integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T",
      crossorigin="anonymous"
    />
    <title>World Sport Center - Add Center</title>
    <style>
      .disable-select {
        user-select: none;
        -webkit-user-select: none;
        -khtml-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
      }
    </style>
    <script>
      //let centers = require('../models/Center');
      let centerName = document.getElementById('center-name');
      let centerAddress = document.getElementById('center-address');
      let centerDescription = document.getElementById('center-description');
      let key = document.getElementById('dev-key');
      function CheckForURL(str)
      {
        let reg = new RegExp('([a-zA-Z\d]+://)?((\w+:\w+@)?([a-zA-Z\d.-]+\.[A-Za-z]{2,4})(:\d+)?(/.*)?)', 'i')
        return reg.test(str)
      }

      async function AddCenter(e)
      {
        e.preventDefault();
      
        if (centerName.value === '') return alert('Please fill in the "Sport Center Name" field');
        else if (centerAddress.value === '') return alert('Please fill in the "Sport Center Address" field');
        else if (centerDescription.value === '') return alert('Please fill in the "Sport Center Description" field');
        else if (key.value === '') return alert('Please fill in the "Developper Key" field');
        else if (CheckForURL(centerDescription.value)) return alert('You can not put a url in the free marker "Sport Center Description" field');
        else if (key.value !== process.env['DEVELOPER_KEY'])
        {
          alert('You filled in the wrong KEY in the "Sport Center Description" field, and this window will self destruct in 10 seconds');
          var timer = setInterval(function() { 
            window.close();
          }, 10000);
          return;
        }

        centers.create({
          type: 'informative',
          name: centerName.value,
          address: centerAddress.value,
          description: centerDescription.value
        });

        if (res.status === 400)
        {
          throw Error('That sport center already exists !');
        }

        alert('Center added !');
        window.location.href = '/';
      };
    </script>
  </head>

  <body>
    <div class="text-center">
      <div class="container my-3">
        <h1 class="display-4 text-center disable-select"> Add Informative Marker </h1>
        <form id="center-form" class="mb-4">
          <div class="form-group">
            <blockquote class="blockquote">
              <p class="mb-0 disable-select">Sport Center Name</p>
            </blockquote>
            <input type="text" id="center-name" class="form-control" />
          </div>
          <div class="form-group">
            <blockquote class="blockquote">
              <p class="mb-0 disable-select">Sport Center Address</p>
            </blockquote>
            <input type="text" id="center-address" class="form-control" />
          </div>
          <div class="form-group">
            <blockquote class="blockquote">
              <p class="mb-0 disable-select">Sport Center Description</p>
            </blockquote>
            <textarea type="text" rows="2" id="center-description" class="form-control" maxlength="150"></textarea>
          </div>
          <div class="form-group">
            <blockquote class="blockquote">
              <p class="mb-0 disable-select">Developper Key</p>
            </blockquote>
            <input type="text" id="dev-key" class="form-control" />
          </div>
          <a href="/api/v1/add" class="btn btn-outline-primary btn-lg"><-- Back</a>
          <button onclick="AddCenter(event)" class="btn btn-lg btn-primary">Submit --></button>
        </form>
      </div>
    </div>
  </body>
</html>

顺便说一句,你做错了很多事情。

  let centerName = document.getElementById('center-name');
  let centerAddress = document.getElementById('center-address');
  let centerDescription = document.getElementById('center-description');
  let key = document.getElementById('dev-key');

像上面一样,所有变量都将为空,因为您在标题中编写了脚本。 该脚本不会在 dom 中找到 dom 元素,因为在 header 中编写的脚本在生成 dom 之前运行。

在您的情况下,最好在生成 dom 后使用脚本。

【讨论】:

    【解决方案3】:

    如果您使用捆绑器,可能无法从主范围访问 AddCenter 函数,请尝试在文件末尾添加 window.AddCenter = AddCenter

    const centers = require('../../models/Center');
    const centerName = document.getElementById('center-name');
    const centerAddress = document.getElementById('center-address');
    const centerDescription = document.getElementById('center-description');
    const key = document.getElementById('dev-key');
    
    function CheckForURL(str)
    {
      let reg = new RegExp('([a-zA-Z\d]+://)?((\w+:\w+@)?([a-zA-Z\d.-]+\.[A-Za-z]{2,4})(:\d+)?(/.*)?)', 'i')
      return reg.test(str)
    }
    
    async function AddCenter(e)
    {
      e.preventDefault();
    
      if (centerName.value === '') return alert('Please fill in the "Sport Center Name" field');
      else if (centerAddress.value === '') return alert('Please fill in the "Sport Center Address" field');
      else if (centerDescription.value === '') return alert('Please fill in the "Sport Center Description" field');
      else if (key.value === '') return alert('Please fill in the "Developper Key" field');
      else if (CheckForURL(centerDescription.value)) return alert('You can not put a url in the free marker "Sport Center Description" field');
      else if (key.value !== process.env['DEVELOPER_KEY'])
      {
        alert('You filled in the wrong KEY in the "Sport Center Description" field, and this window will self destruct in 10 seconds');
        var timer = setInterval(function() { 
          window.close();
        }, 10000);
        return;
      }
    
      centers.create({
        type: 'informative',
        name: centerName.value,
        address: centerAddress.value,
        description: centerDescription.value
      });
    
      if (res.status === 400)
      {
        throw Error('That sport center already exists !');
      }
    
      alert('Center added !');
      window.location.href = '/';
    }
    
    // Add function to global scope
    window.AddCenter = AddCenter
    
    

    【讨论】:

      猜你喜欢
      • 2012-09-13
      • 2021-07-05
      • 1970-01-01
      • 1970-01-01
      • 2013-01-24
      • 1970-01-01
      • 2013-10-10
      • 2018-12-04
      • 2011-12-30
      相关资源
      最近更新 更多