Функция Javascript не анализируется HTML-файлом

#javascript #html #node.js #function

Вопрос:

У меня есть вопрос :

Моя функция AddCenter() не вызывается, когда я нажимаю кнопку HTML.

Редактировать :

Спасибо за все ответы, но это все еще не работает. Итак, вот изменения, которые я внес :
я переместил код в отдельный файл javascript, но он все еще не выполняется.
Предполагается, что он проверяет некоторые значения, которые вводит пользователь, а затем изменяет мой URL с www.mywebsite.example/api/v1/im чтобы www.mywebsite.example/But в этом

случае он меняется с 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-Zd] ://)?((w :w @)?([a-zA-Zd.-] .[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.
 

Комментарии:

1. Ваша проблема заключается в дополнительном ) в конце AddCenter , если вы также удалите () , когда назначаете обработчик нажатия кнопки, и он станет onclick="AddCenter" , то он правильно передаст событие. Я только что проверил, и это работает нормально. Попробуйте удалить опечатку и проверьте консоль разработчика на наличие других ошибок.

Ответ №1:

Когда страница загрузится, ваши переменные будут установлены в значение null. Когда 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();
 

Комментарии:

1. Я думаю, что исключением в этом случае было бы… 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-Zd] ://)?((w :w @)?([a-zA-Zd.-] .[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, так как сценарий, написанный в заголовке, запускается до создания 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-Zd] ://)?((w :w @)?([a-zA-Zd.-] .[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