Jquery is not a function как исправить

I have the jQuery loaded fine, I’ve quadruple-checked, though I’m getting this error in FireBug «$ is not a function» and my code doesn’t work.

Here’s my code:

<script type="text/javascript">
    $("ol li:nth-child(1)").addClass('olli1');
    $("ol li:nth-child(2)").addClass("olli2");
    $("ol li:nth-child(3)").addClass("olli3");
    $("ol li:nth-child(4)").addClass("olli4");
    $("ol li:nth-child(5)").addClass("olli5");
    $("ol li:nth-child(6)").addClass("olli6");
    $("ol li:nth-child(7)").addClass("olli7");
    $("ol li:nth-child(8)").addClass("olli8");
    $("ol li:nth-child(9)").addClass("olli9");
    $("ol li:nth-child(10)").addClass("olli10");
    $("ol li:nth-child(11)").addClass("olli11");
    $("ol li:nth-child(12)").addClass("olli12");
    $("ol li:nth-child(13)").addClass("olli13");
    $("ol li:nth-child(14)").addClass("olli14");
    $("ol li:nth-child(15)").addClass("olli15");
    $("ol li:nth-child(16)").addClass("olli16");
    $("ol li:nth-child(17)").addClass("olli17");
    $("ol li:nth-child(18)").addClass("olli18");
    $("ol li:nth-child(19)").addClass("olli19");
    $("ol li:nth-child(20)").addClass("olli20"); 
</script>

Darko's user avatar

Darko

38.2k15 gold badges79 silver badges106 bronze badges

asked Oct 14, 2010 at 8:51

Alex's user avatar

12

In WordPress jQuery.noConflict() is called on the jQuery file it includes (scroll to the bottom of the file it’s including for jQuery to see this), which means $ doesn’t work, but jQuery does, so your code should look like this:

<script type="text/javascript">
  jQuery(function($) {
    for(var i=0; i <= 20; i++) 
      $("ol li:nth-child(" + i + ")").addClass('olli' + i);
  });
</script>

answered Oct 14, 2010 at 9:09

Nick Craver's user avatar

Nick CraverNick Craver

622k136 gold badges1294 silver badges1155 bronze badges

6

It’s really hard to tell, but one of the 9001 ads on the page may be clobbering the $ object.

jQuery provides the global jQuery object (which is present on your page). You can do the following to «get» $ back:

jQuery(document).ready(function ($) {
    // Your code here
});

If you think you’re having jQuery problems, please use the debug (non-production) versions of the library.

Also, it’s probably not best to be editing a live site like that …

answered Oct 14, 2010 at 9:09

strager's user avatar

stragerstrager

88.5k26 gold badges134 silver badges176 bronze badges

1

<script type="text/javascript">
    $("ol li:nth-child(1)").addClass('olli1');
    $("ol li:nth-child(2)").addClass("olli2");
    $("ol li:nth-child(3)").addClass("olli3");
    $("ol li:nth-child(4)").addClass("olli4");
    $("ol li:nth-child(5)").addClass("olli5");
    $("ol li:nth-child(6)").addClass("olli6");
    $("ol li:nth-child(7)").addClass("olli7");
    $("ol li:nth-child(8)").addClass("olli8");
    $("ol li:nth-child(9)").addClass("olli9");
    $("ol li:nth-child(10)").addClass("olli10");
    $("ol li:nth-child(11)").addClass("olli11");
    $("ol li:nth-child(12)").addClass("olli12");
    $("ol li:nth-child(13)").addClass("olli13");
    $("ol li:nth-child(14)").addClass("olli14");
    $("ol li:nth-child(15)").addClass("olli15");
    $("ol li:nth-child(16)").addClass("olli16");
    $("ol li:nth-child(17)").addClass("olli17");
    $("ol li:nth-child(18)").addClass("olli18");
    $("ol li:nth-child(19)").addClass("olli19");
    $("ol li:nth-child(20)").addClass("olli20"); 
</script>

change this to

    <script type="text/javascript">
        jQuery(document).ready(function ($) {
        $("ol li:nth-child(1)").addClass('olli1');
        $("ol li:nth-child(2)").addClass("olli2");
        $("ol li:nth-child(3)").addClass("olli3");
        $("ol li:nth-child(4)").addClass("olli4");
        $("ol li:nth-child(5)").addClass("olli5");
        $("ol li:nth-child(6)").addClass("olli6");
        $("ol li:nth-child(7)").addClass("olli7");
        $("ol li:nth-child(8)").addClass("olli8");
        $("ol li:nth-child(9)").addClass("olli9");
        $("ol li:nth-child(10)").addClass("olli10");
        $("ol li:nth-child(11)").addClass("olli11");
        $("ol li:nth-child(12)").addClass("olli12");
        $("ol li:nth-child(13)").addClass("olli13");
        $("ol li:nth-child(14)").addClass("olli14");
        $("ol li:nth-child(15)").addClass("olli15");
        $("ol li:nth-child(16)").addClass("olli16");
        $("ol li:nth-child(17)").addClass("olli17");
        $("ol li:nth-child(18)").addClass("olli18");
        $("ol li:nth-child(19)").addClass("olli19");
        $("ol li:nth-child(20)").addClass("olli20"); 
     });
    </script>

answered Jul 18, 2017 at 6:08

Roshan Padole's user avatar

In my case I was using jquery on my typescript file:

import * as $ from "jquery";

But this line gives me back an Object $ and it does not allow to use as a function (I can not use $('my-selector')). It solves my problem this lines, I hope it could help anyone else:

import * as JQuery from "jquery";
const $ = JQuery.default;

answered Mar 13, 2018 at 16:00

Luillyfe's user avatar

LuillyfeLuillyfe

5,9738 gold badges35 silver badges46 bronze badges

1

There are quite lots of answer based on situation.

1) Try to replace ‘$’ with «jQuery»

2) Check that code you are executed are always below the main jquery script.

<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){

});
</script>

3) Pass $ into the function and add «jQuery» as a main function like below.

<script type="text/javascript">
jQuery(document).ready(function($){

});
</script>

answered Feb 14, 2019 at 13:42

Mayank Dudakiya's user avatar

As RPM1984 refers to, this is mostly likely caused by the fact that your script is loading before jQuery is loaded.

answered Oct 14, 2010 at 8:53

mkoistinen's user avatar

mkoistinenmkoistinen

7,6943 gold badges41 silver badges56 bronze badges

1

That error kicks in when you have forgot to include the jQuery library in your page or there is conflict between libraries — for example you be using any other javascript library on your page.

Take a look at this for more info:

  • Using jQuery with other libraries

answered Oct 14, 2010 at 8:58

Sarfraz's user avatar

SarfrazSarfraz

376k77 gold badges531 silver badges578 bronze badges

When jQuery is not present you get $ is undefined and not your message.

Did you check if you don’t have a variable called $ somewhere before your code?
Inspect the value of $ in firebug to see what it is.

Slightly out of the question, but I can’t resist to write a shorter code to your class assignment:

    var i = 1;
    $("ol li").each(function(){
        $(this).addClass('olli' + i++);
    });

answered Oct 14, 2010 at 9:04

Mic's user avatar

MicMic

24.7k9 gold badges56 silver badges69 bronze badges

Use jQuery for $. I tried and work.

answered Jul 31, 2018 at 5:09

Diego Santa Cruz Mendezú's user avatar

I believe using $ alone is now deprecated in the new version of jQuery. Use below syntax instead:

jQuery(function($) {
//magic here
})

answered Jun 18, 2021 at 0:26

Rosalito Udtohan's user avatar

There are two possible reasons for that error:

  1. your jquery script file referencing is not valid
  2. try to put your jquery code in document.ready, like this:

    $(document).ready(function(){

    ….your code….

    });

cheers

answered Oct 14, 2010 at 8:58

Marko's user avatar

MarkoMarko

1,8741 gold badge21 silver badges36 bronze badges

2

Currently, WordPress is the best website builder on the internet. It has gained its popularity due to the many features it offers. However, much like everything else, as good as this CMS may be, it comes with a few issues as well.

One of these issues is the $ is not a function WordPress error. This error can cause your website to display the 404 pages.

In this article, we would like to discuss the $ is not a function WordPress error.

What is the $ is not a function of WordPress Error?

$ is not a function WordPress error occurs when the code comes before the jQuery library. For example, if a plugin or theme calls a code before calling the right library, you get this error.

By default, WordPress doesn’t understand $ as jQuery and you have to make some modifications to fix this error. However, this process could be challenging for some users without any programming knowledge.

$ is not a Function WordPress Error

As always, before making any changes to the core files of WordPress, we recommend you get a full backup of your website. This is a must, because if you misplace a simple “;” you could completely ruin the website.

The backup is there to restore your website back to what it was before you made the modifications.

Use $ instead of jQuery in WordPress

One of the easy fixes is to use $ in WordPress instead of jQuery. You will have to enqueue the script in your theme’s functions.php file.

wp_enqueue_script("jquery");

Most WordPress theme and plugin developers are aware of this issue. Thus, they rather use jQuery instead of the $ sign to be safe.

For example, the normal jQuery anywhere should look like this:

$(“#element”).function();

In WordPress the jQuery looks like this:

jQuery(“#element”).function();

Writing jQuery in a script hundreds of times makes it harder to read and increases the size of the script. It’s recommended that you map jQuery to be mapped to $ in the footer of your website. Simply, copy and paste the following code in the footer file of your theme:

(function($) {
	// console.log($);
})( jQuery );

If you would like to add the code to the header of your theme, simply use the following code:

jQuery(document).ready(function( $ ) {
	// console.log($);
});

With this code, you can write a clean script for your website.

Use a New Name for jQuery

There are many changes you can make to the jQuery, one of them is the ability to change the $ to any particular name you have in mind. To use a new name for jQuery, simply use the following code and replace the name element with the name you have in mind.

var j = jQuery.noConflict();
j( "div p" ).hide();
// Do something with another library's $()
$( "content" ).style.display = "none";

Disable noConflict Mode

To turn off the jQuery.noConflict in WordPress, use the following command:

$ = jQuery.noConflict(true);

This code should turn off the noConflict mode completely.

The $.noConflict command gives you the ability to control the $ variable back to whatever library it was first assigned to. This command makes sure that jQuery doesn’t have any confliction with the $ object of other libraries.

Conclusion

In this article, we discussed the $ is not a function WordPress error. This error is usually caused when your code is called before calling the jQuery and if you are using $ instead of jQuery in WordPress.

By default, WordPress uses jQuery instead of the normal method of $ and this could cause your website to display the 404 error.

You can use a function in both header or footer to change the name $ to your desired name. Besides, you can disable the noConflict mode in WordPress. noConflict mode gives you the ability to control the $ variables and revert them to whatever library they were originally assigned to.

This mode prevents the confliction between the $ object of other libraries.

moslem

Добрый день, сделал шаблон для вордпресса, все отлично работало на локальном хостинге, но когда перенес шаблон уже на рабочий сайт (который уже довольно долгое время функционирует) то вышла выше написанная ошибка, я подозреваю что это из за того что клиент установил кучу всяких плагинов, возможно я неправильно код написал на JS (в чем сомневаюсь, ведь код брал из официальных примеров), вот собственно сам сайт goo.gl/jinL99

Ошибка в файле main.js:3 из за этой ошибки не работает ниже расположенный код, который должен сайт в закладку добавлять.


  • Вопрос задан

    более трёх лет назад

  • 41901 просмотр

В качестве быстрого костыля: используйте jQuery вместо $ в main.js.

Далее, найдите способ убрать jQuery.noConflict(); из perelink_binet.js, от этого все проблемы. Подробнее тут: https://api.jquery.com/jquery.noconflict/

Кроме того, в том же файле используется live, который вроде как выпилен с 1.9 версии, есть шанс, что тоже сломается в этом месте.

Пригласить эксперта

Посмотри внимательно, скорее всего в строке 3 вызвана несуществующая функция, точнее ее нету. Для того что-бы больше что то сказать, скинь код(main.js).

jQuery(function($) {
//Query как $
});

Или

(function($) {
//jQuery как $
})(jQuery);


  • Показать ещё
    Загружается…

25 мая 2023, в 17:50

20000 руб./за проект

25 мая 2023, в 17:40

1 руб./за проект

25 мая 2023, в 17:10

1500 руб./в час

Минуточку внимания

“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

В настоящее время WordPress – лучший конструктор сайтов в Интернете. Он приобрел свою популярность благодаря множеству предлагаемых функций. Однако, как и все остальное, как бы хороша эта CMS ни была, у нее также есть несколько проблем.

Одна из этих проблем – ошибка $ не является функцией WordPress. Эта ошибка может привести к тому, что ваш сайт будет отображать 404 страницы.

В этой статье мы хотели бы обсудить ошибку $ не является функцией WordPress.

Что $ не является функцией ошибки WordPress?

$ не является функцией Ошибка WordPress возникает, когда код находится перед библиотекой jQuery. Например, если плагин или тема вызывает код перед вызовом нужной библиотеки, вы получите эту ошибку.

По умолчанию WordPress не понимает $ как jQuery, и вам необходимо внести некоторые изменения, чтобы исправить эту ошибку. Однако этот процесс может быть трудным для некоторых пользователей без каких-либо знаний в области программирования.

Исправить $ не является ошибкой WordPress функции (простое решение)

Как всегда, перед тем, как вносить какие-либо изменения в основные файлы WordPress, мы рекомендуем сделать полную резервную копию вашего сайта. Это необходимо, потому что если вы потеряете простой символ «;» вы можете полностью испортить сайт.

Резервная копия предназначена для восстановления вашего веб-сайта до того, каким он был до внесения изменений.

Используйте $ вместо jQuery в WordPress

Одно из простых исправлений – использовать $ в WordPress вместо jQuery. Вам нужно будет поставить сценарий в очередь в файле functions.php вашей темы.

wp_enqueue_script("jquery");

Большинство разработчиков тем и плагинов WordPress знают об этой проблеме. Таким образом, для безопасности они скорее используют jQuery вместо знака $.

Например, обычный jQuery в любом месте должен выглядеть так:

$("#element").function();

В WordPress jQuery выглядит так:

jQuery("#element").function();

Написание jQuery в скрипте сотни раз затрудняет чтение и увеличивает размер скрипта. Рекомендуется сопоставить jQuery с символом $ в нижнем колонтитуле вашего веб-сайта. Просто скопируйте и вставьте следующий код в файл нижнего колонтитула вашей темы:

(function($) {
    // console.log($);
})( jQuery );

Если вы хотите добавить код в заголовок своей темы, просто используйте следующий код:

jQuery(document).ready(function( $) {
    // console.log($);
});

С помощью этого кода вы можете написать чистый скрипт для своего сайта.

Используйте новое имя для jQuery

В jQuery можно внести множество изменений, одно из них – это возможность изменить $ на любое конкретное имя, которое вы имеете в виду. Чтобы использовать новое имя для jQuery, просто используйте следующий код и замените элемент name на имя, которое вы имеете в виду.

var j = jQuery.noConflict();
j( "div p" ).hide();
// Do something with another library's $()
$( "content" ).style.display = "none";

Отключить режим noConflict

Чтобы отключить jQuery.noConflict в WordPress, используйте следующую команду:

$ = jQuery.noConflict(true);

Этот код должен полностью отключить режим noConflict.

Команда $ .noConflict дает вам возможность управлять переменной $ обратно в любую библиотеку, которой она была назначена впервые. Эта команда гарантирует, что jQuery не конфликтует с объектом $ других библиотек.

Вывод

В этой статье мы обсудили ошибку $ не является функцией WordPress. Эта ошибка обычно возникает, когда ваш код вызывается перед вызовом jQuery и если вы используете $ вместо jQuery в WordPress.

По умолчанию WordPress использует jQuery вместо обычного метода $, и это может привести к отображению на вашем веб-сайте ошибки 404.

Вы можете использовать функцию как в верхнем, так и в нижнем колонтитуле, чтобы изменить имя $ на желаемое. Кроме того, вы можете отключить режим noConflict в WordPress. Режим noConflict дает вам возможность управлять переменными $ и возвращать их в ту библиотеку, которой они изначально были назначены.

Этот режим предотвращает конфликт между объектом $ других библиотек.

Источник записи: https://betterstudio.com

Понравилась статья? Поделить с друзьями:
  • Как составить заключение об ассортименте
  • Как правильно составить договор займа физических лиц
  • Как найти хороший персонал
  • Найдете дешевле как действует
  • Мужчина который обеспечивает как его найти