How to resolve the conflict between function $ (id) and jquery in js

Source: Internet
Author: User

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;
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.