search
HomeWeb Front-endJS TutorialSummary of JQuery code I have collected over the years_jquery

1. How to create nested filters

Copy code The code is as follows:

//Allow You filter by reducing the matching elements in the collection,
// leaving only those that match the given selector. In this case,
//The query deletes any child nodes that do not (:not) have (:has)
//contain the class "selected" (.selected).
.filter(":not(:has(.selected))")

2. How to reuse element search
Copy Code The code is as follows:

var allItems = $("div.item");
var keepList = $("div#container1 div.item" );
//Now you can continue working with these jQuery objects. For example,
//Crop the "keep list" based on the check box, the name of the check box
//Conforms to
class names:
$(formToLookAt " input:checked").each( function () {
keepList = keepList.filter("." $(this).attr("name"));
});


3 . Any use of has() to check whether an element contains a certain class or element
Copy code The code is as follows:

//jQuery 1.4.* includes support for this has method. This method finds out
//whether an element contains another element class or anything else
//what you are looking for and want to operate on.
$("input").has(".email").addClass("email_icon");

4. How to use jQuery to switch style sheets

Copy code The code is as follows:

//Find out the media type (media-type) you want to switch, Then set the href to the new style sheet.
$('link[media="screen"]').attr('href', 'Alternative.css');


5. How to limit the selection range (based on Optimization purpose)
Copy code The code is as follows:

//Use tag names as much as possible Prefix the class name with
// so that jQuery doesn’t have to spend more time searching for the
// element you want. Another thing to remember is that the more specific the
//operations are for elements on your page, the more
//you can reduce execution and search time. var in_stock = $('#shopping_cart_items input.is_in_stock');

  • Item X

  • Item Y

  • Item Z



6. How to use ToggleClass correctly
Copy code Code As follows:

//The toggle class allows you to add or delete a class based on whether the class's
//exists.
//In this case some developers use: a.hasClass('blueButton') ? a.removeClass('blueButton') : a.addClass('blueButton');
//toggleClass allows you to use The following statement can do this easily
a.toggleClass('blueButton');


7. How to set IE-specific functions
Copy code The code is as follows:

if ($.browser.msie) {
// Internet Explorer is actually not that Easy to use
}

8. How to use jQuery to replace an element
Copy code The code is as follows:

$('#thatdiv').replaceWith('fnuh');

9. How to verify whether an element is empty

Copy code The code is as follows:

if ($('#keks').html().trim()) {
//Nothing found;
}


10. How to find the index number of an element from an unsorted set
Copy code The code is as follows:

$("ul > li").click(function () {
var index = $(this).prevAll().length;
});11. How to put The function is bound to the event
$('#foo').bind('click', function () {
alert('User clicked on "foo."');
});12 . How to append or add html to an element
$('#lal').append('sometext');

13. How to use object literals when creating elements ( literal) to define attributes
Copy code The code is as follows:

var e = $("" , { href: "#", class: "a-class another-class", title: "..." });

14. How to use multiple attributes for filtering
Copy code The code is as follows:

//When using many similar input elements with different types
//This precision-based method is useful var elements = $('#someid input[type=sometype][value=somevalue]').get();15. How to use jQuery to preload Image

jQuery.preloadImages = function () {
for (var i = 0; i $("Summary of JQuery code I have collected over the years_jquery"). attr('src', arguments[i]);
}
}; //Usage$.preloadImages('image1.gif', '/path/to/image2.png', 'some/image3. jpg');

16. How to set event handlers for any element that matches the selector
Copy code The code is as follows:

$('button.someClass').live('click', someFunction);
//Note that in jQuery 1.4.2, delegate and unelegate options
// were introduced instead of live as they provide better context support
// For example, in the case of tables, previously you would use
// .live()
$("table").each(function () {
$("td", this).live("hover", function () {
$(this).toggleClass("hover");
});
});
//Now use
$("table").delegate("td", "hover", function () {
$(this) .toggleClass("hover");
});

17. How to find an option element that has been selected
Copy Code The code is as follows:

$('#someElement').find('option:selected');

18. How to hide an element that contains a certain value text
Copy code The code is as follows:

$ ("p.value:contains('thetextvalue')").hide();

19. If you automatically scroll to a certain area on the page
Copy code The code is as follows:

jQuery.fn.autoscroll = function (selector) {
$('html,body'). animate( { scrollTop: $(this ).offset().top },
500
);
}
//Then scroll to the class/area you want to go to like this .
$('.area_name').autoscroll();

20. How to detect various browsers
Copy code The code is as follows:

if( $.browser.safari) //Detect Safari
if ($.browser.msie && $.browser.version > 6) //Detect IE6 and later versions
if ($.browser.msie && $.browser.version if ($.browser.mozilla && $. browser.version >= '1.8' ) //Detect FireFox 2 and later versions

21. How to replace words in a string
Copy the code The code is as follows:

var el = $('#id'); el.html(el.html().replace(/word/ig , ''));

22. How to disable right-click context menu
Copy code The code is as follows:

$(document).bind('contextmenu', function (e) {
return false ;
});

23. How to define a custom selector
Copy code The code is as follows:

$.expr[':'].mycustomselector = function(element, index , meta, stack){
// element- a DOM element
// index – the current loop index in the stack
// meta – metadata about the selector
// stack – to Stack of all elements in the loop
// Returns true if it contains the current element
// Returns false if it does not contain the current element };
// Usage of custom selector:
$( '.someClasses:test').doSomething(); 24. How to check whether an element exists
if ($('#someDiv' ).length) {
//Your sister, finally found it
}

25. How to use jQuery to detect right and left mouse clicks
Copy code The code is as follows:

$("#someelement").live('click', function (e) {
if ((!$.browser.msie && e .button == 0) || ($.browser.msie && e.button == 1)) {
alert("Left Mouse Button Clicked");
} else if (e.button == 2 ) {
alert("Right Mouse Button Clicked");
}
});

26. How to display or delete the default value in the input field
Copy code The code is as follows:

//This code shows that when the user does not enter a value,
//How to retain a default value in a text input field
//A default value
$(".swap").each(function (i) {
wap_val[i] = $(this ).val();
$(this).focusin(function () {
if ($(this).val() == swap_val[i]) {
$(this).val ("");
}
}).focusout(function () {
if ($.trim($(this).val()) == "") {
$( this).val(swap_val[i]);
}
});
});

27. How to automatically hide or close an element after a period of time (supported Version 1.4)
Copy code The code is as follows:

//This is what we have in 1.3.2 Use setTimeout to implement
setTimeout(function () {
$('.mydiv').hide('blind', {}, 500)
}, 5000);
// This is how you can use the delay() function in 1.4 (this is very similar to hibernation)
$(".mydiv").delay(5000).hide('blind', {}, 500);28. How to dynamically add created elements to DOM
var newDiv = $('');
newDiv.attr('id', 'myNewDiv').appendTo('body' );

29. How to limit the number of characters in the "Text-Area" field
Copy code The code is as follows:

jQuery.fn.maxLength = function (max) {
this.each(function () {
var type = this.tagName.toLowerCase() ;
var inputType = this.type ? this.type.toLowerCase() : null;
if (type == "input" && inputType == "text" || inputType == "password") {
this.maxLength = max;
}
else if (type == "textarea") {
this.onkeypress = function (e) {
var ob = e || event;
var keyCode = ob.keyCode;
var hasSelection = document.selection
? document.selection.createRange().text.length > 0
: this.selectionStart != this.selectionEnd;
return !(this.value.length >= max
&& (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13)
&& !ob.ctrlKey && !ob.altKey && !hasSelection);
};
this.onkeyup = function () {
if (this.value.length > max) {
this.value = this. value.substring(0, max);
}
};
}
});
}; //Usage$('#mytextarea').maxLength(500);

30. How to create a basic test for a function
Copy the code The code is as follows:

//Put the test separately in the module
module("Module B");
test("some other test", function () {
//Indicate the internal expectations of the test How many assertions to run
expect(2);
//A comparison assertion, equivalent to JUnit’s assertEquals
equals(true, false, "failing test");
equals(true, true, "passing test");
}); 31. How to clone an element in jQuery

var cloned = $('#somediv').clone();

32. How to test whether an element is visible in jQuery
Copy the code The code is as follows:

if ($(element).is(':visible') ) {
//The element is visible
}

33. How to put an element in Center position of the screen
Copy code The code is as follows:

jQuery.fn.center = function ( ) {
this.css('position', 'absolute');
this.css('top', ($(window).height() - this.height()) / $(window) .scrollTop() 'px');
this.css('left', ($(window).width() - this.width()) / 2 $(window).scrollLeft() 'px') ;
return this;
} //Use the above function like this: $(element).center();

34. How to return all elements with a specific name The values ​​​​are placed in an array
Copy code The code is as follows:

var arrInputValues ​​= new Array();
$("input[name='table[]']").each(function () {
arrInputValues.push($(this ).val());
} ; >
(function ($) {
$.fn.stripHtml = function () {
var regexp = /])*>/gi;
this.each(function () { $(this).html($(this).html().replace(regexp, "")); }); return $(this); } })(jQuery); //Usage: $('p').stripHtml();
36. How to use closest to get the parent element




Copy code


The code is as follows:

$('#searchBox').closest('div');

37. How to log jQuery events using Firebug and Firefox
Copy Code The code is as follows:
// Allow chain logging
// Usage:
$('#someDiv').hide() .log('div hidden').addClass('someClass');
jQuery.log = jQuery.fn.log = function (msg) { if (console) { console.log(" %s: %o", msg, this); } return this; };
38. How to force a link to open in a pop-up window




Copy code


The code is as follows:

jQuery('a.popup').live('click', function () {
newwindow = window.open($(this).attr('href'), '', 'height=200,width=150');
if (window.focus) {
newwindow.focus(); } return false; }); 39. How to force a link to open in a new tab


Copy code


The code is as follows:

jQuery('a.newTab').live('click', function () {
newwindow = window.open($(this).href);
jQuery(this).target = "_blank";

Copy code


The code is as follows:

// Don’t do this
$('#nav li').click(function () {
$('#nav li').removeClass('active');
41. How to toggle all checkboxes on the page
Copy code The code is as follows:

var tog = false ;
// Or true if they are selected when loading

$('a').click(function () {
$( "input[type=checkbox]").attr("checked", !tog);
tog = !tog;
});

42. How to based on some input text To filter a list of elements
Copy code The code is as follows:

//If the value of the element and If the input text matches
//The element will be returned $('.someClass').filter(function () {
return $(this).attr('value') == $(' input#someId').val();
})

43. How to get the mouse pad cursor position x and y
Copy the code The code is as follows:

$(document).ready(function () {
$(document).mousemove(function (e) {
$('#XY').html("X Axis : " e.pageX " | Y Axis " e.pageY);
});
});

44. How to make the entire List Element (LI) clickable
Copy code The code is as follows:

$("ul li").click(function () {
window.location = $(this).find("a").attr("href");
return false;
});

45. How to use jQuery to parse XML (basic example)
Copy code The code is as follows:

function parseXml(xml) {
//Find each Tutorial and print out the author
$(xml).find("Tutorial").each(function () {
$("#output").append($(this ).attr("author") "");
});
}

46. How to check if the image has been fully loaded
Copy code The code is as follows:

$('#theImage').attr('src', 'image.jpg') .load(function () {
alert('This Image Has Been Loaded');
});

47. How to use jQuery to specify a namespace for events
Copy code The code is as follows:

//The event can be bound to the namespace like this
$(' input').bind('blur.validation', function (e) {
// ...
});

//data method also accepts namespace
$( 'input').data('validation.isValid', true);

48. How to check whether cookies are enabled
Copy code The code is as follows:

var dt = new Date();
dt.setSeconds(dt.getSeconds() 60);
document.cookie = "cookietest=1; expires=" dt.toGMTString();
var cookiesEnabled = document.cookie.indexOf("cookietest=") != -1;
if (!cookiesEnabled) {
// Cookies are not enabled
}

49. How to expire cookies
Copy code The code is as follows :

var date = new Date();
date.setTime(date.getTime() (x * 60 * 1000));
$.cookie('example', 'foo', { expires: date });50. How to use a clickable link to replace any URL in the page

$.fn.replaceUrl = function () {
var regexp =
/( (ftp|http|https)://(w :{0,1}w*@)?(S )(:[0-9] )?(/|/([w#!:.? =&% @!-/]))?)/gi;
this.each(function () {
$(this).html(
$(this).html().replace(regexp, ' $1')
);
});
return $(this);
} //Usage $('p' ).replaceUrl();

It’s finally finished. Typesetting is also a laborious task. The resources are compiled from the Internet and are given to those children’s shoes who have not collected them. If you have already collected them, please do not throw bricks.

(Thank you for your feedback, the errors have been corrected, I hope I didn’t mislead you)
PS: Due to the correction of errors, the layout is messed up, so I am re-posting it now.
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),