Добрый день читатели! Сегодня речь пойдет об очень-очень популярной ошибке, которая может возникать в CMS Joomla.
Представьте ситуацию. У вас сайта на Joomla, вы хотите, допустим, вставить сторонний скрипт, например, форму обратной связи на ajax. Вы точно знаете, что эта форма рабочая, не один раз ее использовали и тестировали. Вставляете на ваш сайт на joomla. Проверяете нажимая “отправить” и бамц – ничего не происходит.
В такой ситуации, первым делом вы будете проверять, подключен ли jquery вообще и правильная ли версия. Если вы уверенны, что все сделали правильно, но форма все равно не работает, необходимо проверить firebug консоль, чтобы понять, какую ошибку она вызывает.
В нашем случае ошибка будет
$(document).ready is not a function
По умолчанию в joomla используются некоторые js-фреймворки. Один из таких фреймворков – motools, который переписывает символ $, который вы пытаетесь использовать в ваших скриптах.
Решение проблемы
В вашем скрипте необходимо заменить все “$” на “jQuery”.
Например, если у вас написано
var posName = $("#posName").val();
То вы должны заменить на
var posName = jQuery("#posName").val();
Или у вас
$(document).ready(function()
А должно быть
jQuery(document).ready(function()
И т.д.
Вот и все 🙂 Решение проблемы не очень сложное. Если возникли вопросы, пишите в комментариях
Вопрос:
Я использую JQuery для получения json-объекта с сервера solr. Когда я запускаю свой html файл с Tomcat, он отлично работает, но когда я вставляю его в свой проект, который работает в weblogic, он получает эту ошибку: (отладка выполняется через firebug)
$ is not defined
$(document).ready(function(){
Почему я получаю эту ошибку, когда я вставляю ее в свой проект?
Это содержимое моего тега <head>. Вот как я включаю jquery.js:
<head>
<title>Search Result </title>
<style>
img{ height: 150px; float: left; border: 3;}
div{font-size:10pt; margin-right:150px;
margin-left:150px; }
</style>
<script type="text/javascript" src="jquery-1.6.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){ //Error happens here, $ is not defined.
});
</script>
</head>
Лучший ответ:
Вы загрузили jQuery в разделе head? Вы правильно загрузили его?
<head>
<script src="scripts/jquery.js"></script>
...
</head>
Этот код предполагает, что jquery.js находится в каталоге scripts. (Вы можете изменить имя файла, если хотите)
Вы также можете использовать jQuery размещенный Google:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
...
</head>
Согласно вашему комментарию:
По-видимому, ваш веб-сервер не настроен на возврат jQuery-1.6.1.js при запросе /webProject/jquery-1.6.1.js. Для этого может быть множество причин, таких как неправильное имя файла, имя папки, параметры маршрутизации и т.д. Вам нужно создать другой вопрос и описать ваш 404 более подробно (например, имя локального файла, операционную систему, имя веб-сервера и настройки).
Опять же, вы можете использовать jQuery, как указано в Google (см. выше), однако вы все равно можете узнать, почему некоторые локальные файлы не получают по запросу.
Ответ №1
Я нашел, что нам нужно иногда использовать noConflict:
jQuery.noConflict()(function ($) { // this was missing for me
$(document).ready(function() {
other code here....
});
});
Из документов:
Многие библиотеки JavaScript используют $как имя функции или переменной, как это делает jQuery. В случае jQuery
$является просто псевдонимом для jQuery, поэтому вся функциональность доступна без использования$. Если вам нужно использовать другую библиотеку JavaScript вместе с jQuery, верните элемент управления$обратно в другую библиотеку с вызовом$.noConflict(). Старые ссылки$сохраняются во время инициализации jQuery;noConflict()просто восстанавливает их.
Ответ №2
Вы получаете эту ошибку только в том случае, если jQuery некорректно загружен, вы можете проверить с помощью firebug, что URL-адрес его пытается загрузить, чтобы вы могли видеть, неверен ли ваш относительный путь.
Кроме того, в отдельной заметке вы можете использовать $(function(){ как сокращенное обозначение $(document).ready(function(){
Ответ №3
Если у вас есть js файл, который ссылается на jquery, это может быть связано с тем, что файл js находится в теле, а не в главном разделе (это была моя проблема). Вы должны перенести свой файл js в раздел главы ПОСЛЕ ссылки jquery.js.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js"></script>
<script src="myfile.js" type="text/javascript"></script>
</head>
<body>
</body>
</html>
Ответ №4
см. для вашего пути js, который может быть причиной… потому что вы получите эту ошибку только в том случае, если jQuery неправильно загружен.
Ответ №5
У меня такая же проблема… на http://www.xaluan.com.. но после журнала. Я узнаю, что после запуска jQuery я создаю функцию, используя один элемент id, который не существует.
Например:
$('#aaa').remove() <span class="aaa">sss</spam>
поэтому id="aaa" не существовало.. тогда jQuery перестает работать.. потому что такие ошибки
Ответ №6
Использование:
jQuery(document).ready(function($){
// code where you can use $ thanks to the parameter
});
Или его более короткая версия:
jQuery(function($){
// code where you can use $ thanks to the parameter
});
Ответ №7
У меня была эта проблема, и из-за меня я пытался включить jQuery через http, пока моя страница была загружена как https.
Ответ №8
У меня была такая же проблема в Chrome, где мои скрипты были такими:
<script src="./scripts/jquery-1.12.3.min.js"></script>
<script src="./scripts/ol-3.15.1/ol.js" />
<script>
...
$(document).ready(function() {
...
});
...
</script>
Когда я изменил на:
<script src="./scripts/jquery-1.12.3.min.js"></script>
<script src="./scripts/ol-3.15.1/ol.js"></script>
$(document).ready был вызван.
Let us say I have a HTML page that contains a javascript file:
The base.js is like this:
$(document).ready(function () {
obj.init();
}
// ..............
var obj = {...};
Surprisingly, sometimes(not all the time) Firebug shows me the undefined error on obj.init() call! My understanding is that document ready means all html elements, including images, javascript files downloaded and executed(?).
I believe in order to find the root cause of this error, we need understand what exactly the «document ready» means? anybody has any insight?
============================
Update: maybe I should not mention about image over here, my main concern is regarding the javascript file in particular. Does «DOM fully constructed» include «all javascript code executed»?
============================
Update again: It seems people here agreed that event «document.ready» WILL NOT be triggered until ALL javascript code got downloaded and executed. Thus, root cause of the issue remain unknown. I did bypassed this issue after I moved the $(document).ready block to the bottom of the javascript file.
Let us say I have a HTML page that contains a javascript file:
The base.js is like this:
$(document).ready(function () {
obj.init();
}
// ..............
var obj = {...};
Surprisingly, sometimes(not all the time) Firebug shows me the undefined error on obj.init() call! My understanding is that document ready means all html elements, including images, javascript files downloaded and executed(?).
I believe in order to find the root cause of this error, we need understand what exactly the «document ready» means? anybody has any insight?
============================
Update: maybe I should not mention about image over here, my main concern is regarding the javascript file in particular. Does «DOM fully constructed» include «all javascript code executed»?
============================
Update again: It seems people here agreed that event «document.ready» WILL NOT be triggered until ALL javascript code got downloaded and executed. Thus, root cause of the issue remain unknown. I did bypassed this issue after I moved the $(document).ready block to the bottom of the javascript file.
“Error: $ is not a function”, this is the error that was being thrown back at me while working on a WordPress site the other day. However for the life of me I couldn’t see why my, usual fine JavaScript code, was failing. Was it a problem with my jQuery code, my WordPress installation or both?
I reduced my code down to producing an alert when the DOM was ready, but still it threw the error:
Error: $ is not a function
Well I’m sure we’ve all had this error before, usually when we break or incorrectly reference the jQuery core library. However I doubled checked and it was definitely pointing to the right file.
After a little spree on Google and a bit of research, I found that WordPress loads jQuery in a ‘no-conflicts’ mode to significantly reduce the likelihood of it conflicting with other third party libraries that a owner may install on their blog/site.
What this means in my scenrario, was exactly what the error stated. In ‘no conflict’ mode the $ shortcut is disabled, so you must replace it with the word ‘jQuery’ (notice the capitalised Q).
So if you had a piece of script such as:
[js]$(document).ready(function() {
$(«.someClass»).hide();
$(«#elementID .anotherClass»).eq(2).show();
…
}[/js]
You’d replace all the dollar symbols with the string ‘jQuery’.
[js]jQuery(document).ready(function() {
jQuery(«.someClass»).hide();
jQuery(«#elementID .anotherClass»).eq(2).show();
…
}[/js]
So thats one way to circumnavigate the conflict free wrapper that WordPress applies to jQuery.
Another approach, jQuery and conflict modes…
In my situation I was importing some large chunks of jQuery code libraries, so I didn’t really want to duplicate my existing libraries just for the purposes of having one in ‘normal’ mode and one in ‘no-conflicts’ mode.
Then I read you can easily override the ‘no-conflict’ compatibility mode, score! Now normally you shouldn’t just jump in and override such a system, it is there for a reason you know! The WordPress system is built by some very brainy people, much better than myself, so if they think its a requirement for a vanilla install of their system then so be it. However with the project I was working on, I knew exactly what was installed already, and that no further plugins will be scheduled to be installed for a long time. Either way I dropped a few comments in the top of the jQuery source file, as well as a ReadMe file in the jQuery directory, just in case in the future it did become a problem.
Anyway… the solution turned out to be simple passing the dollar shortcut in as a argument for the ready function applied to the document. So our example code becomes:
[js]jQuery(document).ready(function( $ ) {
$(«.someClass»).hide();
$(«#elementID .anotherClass»).eq(2).show();
…
}[/js]
Notice we still have to use the conflict free wrapper to begin with, but once the page is ready the dollar shortcut will work for your existing code. So no need to go changing those libraries!
Hope that helps someone out, I was nearly tearing my hair out trying to work out why the error “$ is not a function” was being thrown