1. 程式人生 > 其它 >$j is not a function

$j is not a function

$j is not a function

You need to add this code to make it working (JQUERY noConflict)

var $j = $.noConflict();

This will allow you to use $j instead of $.

Why do some sites use jquery with a $j instead of just a $?

回答1

You can define, how you want to call the jquery functionality. Maybe this site uses another library, which reserves the $, and for that reason used the alias $j.

回答2

This is to avoid colision with other libraries with:

 jQuery.noConflict();

For instance some libraries like prototype also use the $ sign, and if you end up using both it will most likely break. If you developed your jquery functions using $j it won't.

回答3

It's simply a method to avoid naming conflicts. Many JavaScript libraries (jQuery happens to be one of them) uses $ as a shortcut. For more information, see

jQuery.noConflict()

Replace $j with JQuery

這裡的做法太極端了,直接把jQuery原生程式碼裡面修改了,這會導致其他問題。

Why we have to use $.noConflict() in jQuery?

I know we are using $.noConflict() to overcome other plugin conflicts. For example, if some new plugin use the $ symbol as a variable it will override. so, we are using like below

var $j=$.noConflict();

But, i am having doubt here, We can archive this using below code itself then why $.noConflict(); needed?

 var $j=$;

Thanks advance. Kindly explain major different

回答

Here you got detailed information about why:

Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $. If you need to use another JavaScript library alongside jQuery, return control of $ back to the other library with a call to $.noConflict(). Old references of $ are saved during jQuery initialization; noConflict() simply restores them.

It's from jQuery and there is even more information: https://api.jquery.com/jquery.noconflict/

Update after comment

From jQuery code https://code.jquery.com/jquery-1.10.2.js if you search for noConflict you will find

noConflict: function( deep ) {
        if ( window.$ === jQuery ) {
            window.$ = _$;
        }

        if ( deep && window.jQuery === jQuery ) {
            window.jQuery = _jQuery;
        }

        return jQuery;
    },

In simple: This checks if global $ or global jQuery has already been used. Either way it will return jQuery. So you can not just do var $j=$; cause $ may already has conflicts. The noConflict() is what you need.