This article introduces how to solve the conflict between function $ (id) and jquery in js. If you have encountered such problems, refer.
$ (Id) is js document. the abbreviation of getElementById (id) defines the $ ("img-icon") that can be directly used when this method is called later "). onclick is a simple encapsulation. So many people like to write:
The Code is as follows: |
Copy code |
Var $ = function (id ){ Return document. getElementById (id ); }; |
However, this type of js Code conflicts with the function used to obtain JQuery objects, causing JQuery to fail to obtain objects and the following error occurs: Uncaught TypeError: cannot set property 'onclick' of null.
You can write security statements in this way.
The Code is as follows: |
Copy code |
Var $ id = function (id ){ Return "string" = typeof id? Document. getElementById (id): id; }; |
Or:
The Code is as follows: |
Copy code |
Var $ id = function (id ){ Return typeof id = "string "? Document. getElementById (id): id; }; |
Or:
The Code is as follows: |
Copy code |
Function $ (id ){ If (typeof jQuery = 'undefined' | (typeof id = 'string' & document. getElementById (id ))){ Return document. getElementById (id ); } Else if (typeof id = 'object' |! /^ W * $/. exec (id) | /^ (Body | div | span | a | input | textarea | button | img | ul | li | ol | table | tr | th | td) $ /. exec (id )){ Return jQuery (id ); } Return null; } |