ホームページ > 記事 > ウェブフロントエンド > JQuery の $namingconflict_jquery の詳細な分析
Jquery では、$ は JQuery のエイリアスです。たとえば、$('#msg') は JQuery('#msg') と同等です。ただし、複数の js ライブラリを導入し、別の js ライブラリでも $ 記号が定義されている場合、$ 記号を使用すると競合が発生します。以下はjquery.jsとprototype.jsという2つのライブラリファイルを導入する例です。
最初のケース: jquery.js は、prototype.js の後に導入されます。たとえば、
(function($){})(jQuery)
1 First of all, (function(){})() is written to create an anonymous method and execute it immediately (function(){}). This is the parentheses after the anonymous method, which calls this method immediately. ).
Doing this can create a scope to ensure that internal variables do not conflict with external variables, such as $jQuery and other variables defined within jquery.
2 (function($){})(jQuery) The main function of this writing method is to ensure that jquery does not conflict with other class libraries or variables. First, it is necessary to ensure that the variable name of jQuery does not conflict with the outside world (jquery internal $ and jQuery are the same thing. The reason why they have two names is that they are afraid that $ will conflict with other variable names (the probability of jQuery conflicting with other variables is very small) and pass in an anonymous object. The anonymous object names the parameter $ (actually the same as jquery The internals are the same) Then you can freely write your plug-in in (function($){})(jQuery) without having to consider whether there is a conflict with external variables