Home > Web Front-end > JS Tutorial > body text

Summary of JQuery code I have collected over the years_jquery

WBOY
Release: 2016-05-16 17:51:21
Original
875 people have browsed it

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 < arguments.length; i ) {
$(""). 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 <= 6) //Detect IE6 and earlier versions
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.
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template