Курсы javascript
Приветствую!
В JS я топор. Прощу помощи
Пытаюсь вызвать JS функцию в HTML таким методом:
<script type="text/javascript" language="javascript">
showAddress(‘Москва, ул.Самокатная, д.1., стр.21’)
</script>
но ничего не выходит.
Если же я прописываю так:
<a href="javascript :showAddress(‘Москва, ул.Самокатная, д.1., стр.21’)">Москва, ул.Самокатная, д.1., стр.21</a>
то при нажатии на ссылку все работает.
Как мне сделать чтобы функция запускалась автоматом не нажимая на ссылку?
почему тогда она так выполняется
<a href="javascript :showAddress(‘Москва, ул.Самокатная, д.1., стр.21’)">Москва, ул.Самокатная, д.1., стр.21</a>
а да точно.
саму функцию я объявляю в <head> документа
<script src="http://api-maps.yandex.ru/1.1/index.xml?key=AAxdPlMBAAAAtF8OewMAdeohAZP2V7UNQIga GBL1CzxrEf0AAAAAAAAAAACSv_9W2SVDOURAo9v_4FDuNoFBbQ ==" type="text/javascript"></script>
<script type="text/javascript">
var map, geoResult;
Что пошло не так? Устранение ошибок JavaScript
Когда вы создали игру «Угадай номер» в предыдущей статье, вы, возможно, обнаружили, что она не работает. Не бойтесь — эта статья призвана избавить вас от разрыва волос над такими проблемами, предоставив вам несколько простых советов о том, как найти и исправить ошибки в программах JavaScript.
| Нужно: | базовая компьютерная грамотность, базовое понимание HTML и CSS, понимание того, что такое JavaScript. |
|---|---|
| Цель | получить способность и уверенность в том, чтобы приступить к исправлению простых проблем в вашем собственном коде. |
Типы ошибок
Когда вы делаете что-то не так в коде, есть два основных типа ошибок, с которыми вы столкнётесь:
- Синтаксические ошибки: Это орфографические ошибки в коде, которые фактически заставляют программу вообще не запускаться, или перестать работать на полпути — вам также будут предоставлены некоторые сообщения об ошибках. Обычно они подходят для исправления, если вы знакомы с правильными инструментами и знаете, что означают сообщения об ошибках!
- Логические ошибки: Это ошибки, когда синтаксис действительно правильный, но код не тот, каким вы его предполагали, что означает, что программа работает успешно, но даёт неверные результаты. Их часто сложнее находить, чем синтаксические ошибки, так как обычно не возникает сообщение об ошибке, которое направляет вас к источнику ошибки.
Ладно, все не так просто — есть и другие отличия, которые вы поймёте, пока будете изучать язык JavaScript глубже. Однако вышеуказанной классификации достаточно на раннем этапе вашей карьеры. Мы рассмотрим оба эти типа в дальнейшем.
Ошибочный пример
Чтобы начать работу, давайте вернёмся к нашей игре с угадыванием чисел — за исключением того, что мы будем изучать версию с некоторыми преднамеренными ошибками. Перейдите в Github и сделайте себе локальную копию number-game-errors.html (см. здесь как это работает).
- Чтобы начать работу, откройте локальную копию внутри вашего любимого текстового редактора и вашего браузера.
- Попробуйте сыграть в игру — вы заметите, что когда вы нажимаете кнопку «Submit guess», она не работает!
Примечание: Возможно, у вас может быть собственная версия игрового примера, которая не работает, которую вы можете исправить! Мы по-прежнему хотели бы, чтобы вы работали над статьёй с нашей версией, чтобы вы могли изучать методы, которые мы здесь преподаём. Затем вы можете вернуться и попытаться исправить ваш пример.
На этом этапе давайте рассмотрим консоль разработчика, чтобы увидеть, можем ли мы видеть какие-либо синтаксические ошибки, а затем попытаемся их исправить. Вы узнаете, как это сделать, ниже.
Исправление синтаксических ошибок
Раньше в курсе мы заставили вас набрать некоторые простые команды JavaScript в консоль разработчика JavaScript (если вы не можете вспомнить, как открыть это в своём браузере, следуйте предыдущей ссылке, чтобы узнать, как это сделать). Что ещё более полезно, так это то, что консоль предоставляет вам сообщения об ошибках всякий раз, когда существует синтаксическая ошибка внутри JavaScript, которая подаётся в механизм JavaScript браузера. Теперь пойдём на охоту.
- Перейдите на вкладку, в которой у вас есть number-game-errors.html, и откройте консоль JavaScript. Вы должны увидеть сообщение об ошибке в следующих строках:

- Это довольно простая ошибка для отслеживания, и браузер даёт вам несколько полезных бит информации, которые помогут вам (скриншот выше от Firefox, но другие браузеры предоставляют аналогичную информацию). Слева направо, у нас есть:
- Красный «x» означает, что это ошибка.
- Сообщение об ошибке, указывающее, что пошло не так: «TypeError: guessSubmit.addeventListener не является функцией»
- Ссылка «Узнать больше», которая ссылается на страницу MDN, которая объясняет, что эта ошибка означает в огромных количествах деталей.
- Имя файла JavaScript, который ссылается на вкладку «Отладчик» консоли разработчика. Если вы перейдёте по этой ссылке, вы увидите точную строку, где подсвечивается ошибка.
- Номер строки, в которой находится ошибка, и номер символа в этой строке, где первая ошибка. В этом случае у нас есть строка 86, символ номер 3.
- Если мы посмотрим на строку 86 в нашем редакторе кода, мы найдём эту строку:
**Примечание:**См. наш TypeError: «x» не является справочной страницей функций для получения дополнительной информации об этой ошибке.
Синтаксические ошибки: второй раунд
Примечание: console.log() это часто используемая функция отладки, которая выводит значение в консоль. Поэтому она будет выводить значение lowOrHi в консоли, как только мы попытаемся установить его в строке 48.
- Сохраните и обновите страницу, и вы увидите, что ошибка исчезла.
- Теперь, если вы попробуете ввести значение и нажать кнопку «Submit guess», вы увидите . другую ошибку!

- На этот раз сообщается об ошибке: «TypeError: lowOrHi is null», в строке 78.
Примечание: Null — это специальное значение, которое означает «ничего» или «не значение». Поэтому lowOrHi был объявлен и инициализирован без значения — у него нет типа или значения.
Примечание: Эта ошибка не появилась, как только страница была загружена, потому что эта ошибка произошла внутри функции (внутри checkGuess() < . >блока). Об этом вы узнаете более подробно в нашей более поздней статье о функциях, код внутри функций выполняется в отдельной области для кода внешних функций. В этом случае код не был запущен, и ошибка не была брошена до тех пор, пока функция checkGuess() не была запущена строкой 86.
Why Is My JavaScript Not Working? (With Examples)
We round up the most common causes for your JavaScript code not working.

So the JavaScript tag you just added to your website isn’t working, and you want to get to the meat of the problem so you can fix it.
As any experienced developer will tell you, there’s more than one reason why this can happen. And, depending on how complex your code, finding that reason out can take you anywhere from a couple of minutes to hours of googling and debugging.
Hoping to help save you some time, in this post I’ve compiled a list of the most common mistakes that can make your JavaScript code “not work.”
Issues With the Tag
If your JavaScript code is not working, the first thing you should do is check the <script> tag.
When you include JavaScript in your HTML document with the <script> tag, many things can (and often do) go wrong. And, to avoid chasing a red herring, it’s best to rule them out before looking for other possible causes.
Misspelled Tag
Carefully inspect the <script> tag and the type="text/javascript" attribute.
Have you misspelled anything? Have you omitted a forward slash (/), quotation mark (‘), less-than (<) or greater-than (>) sign?
These mistakes happen more often than we think, especially when we work late into the night, with a reduced attention span, to meet tight deadlines.
Below, I’ve listed a few examples for things that can go wrong:
Wrong Relative Path or URI
If you’re loading your script from another location, such as your server or a CDN, make sure you’re using the right URI. In case you are, check if the file is still there.
Suppose you’re loading the script from your own server, and you’re doing it with a relative path. Check that relative path and make sure it’s correct.
If you’re loading the script from a CDN, try to open the URI in your browser and see if the file is still there. Scripts, especially libraries, are often updated—and legacy versions get deprecated.
Wrong Tag Placement
If your <script> tag contains code that needs to parse and manipulate the DOM elements in the HTML markup, you probably want to include it at the bottom of the <body> tag instead of the top of the <head> tag.
Not all scripts that should have a listener for the DOMContentLoaded event have it, and loading scripts that need to read the DOM before the DOM has been fully loaded is a very, very common issue.
For example, the following JavaScript code snippet won’t work because the tag is implemented in the HTML document’s <head> and, when it tries to select div#say-hello , it won’t be loaded and parsed by the browser window yet:
There are two solutions to this.
One is to add an event listener for the DOMContentLoaded event:
The other is to place the tag immediately before the closing of the <body> tag:
Both of these solutions will fire the JavaScript code after the DOM element it needs to query for has been fully loaded and parsed by the browser.
Issues With the Code
Equally common are issues with the code itself, more often than not due to fatigue or haste. Chief among them are (1) mistyped function or variable names and (2) misused declarations.
The good news is that, by inspecting the error messages in the browser’s console, you can catch these quickly and easily because they tend to throw:
- ReferenceError when you’re using the wrong name to reference a function or variable.
- SyntaxError when you’ve mistyped something or omitted a character inside your function’s statement.
Try to rule these out before you continue debugging your code.
Mistyped Names
If you mistype your function’s name:
Or a constant’s or variable’s name within your function:
You will see an Uncaught ReferenceError in the browser’s console.
Wrong Syntax
If you’re a Full-Stack Developer and you keep switching back and forth between HTML/CSS and JavaScript on the frontend and whatever language you’re using on the backend, it’s only a matter of time until you make a mistake and mix up the syntax between languages.
When in doubt, check the syntax of:
- Parenthesis () after if , elseif , for , while statements.
- Curly brackets <> for individual statement blocks (pay extra attention to statements within statements, a.k.a. nested statements).
- Square brackets [] and new Array() method for arrays.
- Quotation marks for strings (pay extra attention to quotes within quotation marks, a.k.a. nested quotes).
- Uses of JavaScript methods and operators to store, manipulate, and compare data in objects (Are you using the right ones?).
- Semicolons ; between statements in a loop.
My two go-to references for syntax are MDN Web Docs and this JavaScript cheat sheet.
Const, Let, and Var Declarations
In JavaScript, you can declare values using const , let , and var .
The declaration you opt for has important implications for your code because it determines what you can—and cannot—do to the data item/s you just stored in the memory.
As a general rule of thumb, here’s how to choose between the const , let , and var declarations in JavaScript:
- Use const to declare a read-only constant.
- Use let to declare a local variable limited to the scope of the block statement it’s declared in (as well as any sub-blocks).
- Use var to declare a global variable or local variable limited to the function it’s declared in.
With all that said, let us take a look at some of the top issues pertaining from the limitations of these three declarations in JavaScript.
Trying to redeclare a constant:
You can’t redeclare a const . If you try to do it, as shown in the example below, the browser will throw an Uncaught SyntaxError back at you:
Expectedly, if you’re trying to redeclare a constant with updated values, it won’t work and it may break the flow of data within your application.
Trying to redeclare a let variable in the same statement:
A let variable can only be declared once within a single statement. (But it can be reassigned as many times as you need it to.)
This means that you can reuse variable names, like x , y , and z across functions and statements—as long as you don’t try to do so within the same bracket or sub-bracket.
Keep this in mind, especially if you’re new to JavaScript or if you’re experienced with it, but you’ve only recently started to use let declarations in your code. This is a subtle constraint, and it can cause just as subtle bugs. 🙂
1 comment
thank you very much for help otherwise i lost my two days to findout what is wrong, but it was only a single a spelling mistake, i wrote scipt instead of write script.Thanks again.
sorry if any english mistake because i am not good in english.
Leave a comment Cancel reply

report this ad
-
July 16, 2023 July 13, 2023 July 13, 2023 July 13, 2023 July 13, 2023
About
We publish growth advice, technology how-to’s, and reviews of the best products for entrepreneurs, creators, and creatives who want to write their own story.
Disclaimer
Maker's Aid is a participant in the Amazon Associates, Impact.com, and ShareASale affiliate advertising programs.
These programs provide means for websites to earn commissions by linking to products. As a member, we earn commissions on qualified purchases made through our links.
Explore
Tools

report this ad
To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.
Не работает java script во внешнем файле. В html файле — работает
Некоторые скрипты перестали работать. Т.е. в теле документа — работают, а во внешнем файле — нет. Скажите почему так?
<script defer src=»http://site.ru/script.js»></script>
Вот скриптs которые не работают во внешнем файле (это AJAX):
- eTarget 2011:Панельная дискуссия «Стратегия и планирование рекламной кампании в интернете»
- eTarget 2011: Круглый стол «Реклама в онлайн-видео»
- Могут ли «плохие» входящие ссылки привести к ухудшению ранжирования?
что консоль показывает?
Попробуйте без атрибута defer тег использовать.
Ну и на всякий случай, страница у вас не по https открывается? Тогда и скрипт надо по https запрашивать.