Home Web Front-end JS Tutorial Share 15 jquery tips that everyone is familiar with_jquery

Share 15 jquery tips that everyone is familiar with_jquery

May 16, 2016 pm 03:28 PM
jquery Skill

15 well-known jquery tips to help improve your jQuery application, share with everyone

  • Back to top button
  • Image preloading
  • Determine whether the image has been loaded
  • Automatically repair damaged images
  • Hover switch class
  • Disable input
  • Stop loading links
  • toggle fade/slide
  • Simple accordion
  • Make two DIVs the same height
  • Open external link in browser tab/new window
  • Get elements based on text
  • Trigger of visible changes
  • Ajax call error handling
  • Chain operation

1. Back to top button

Using the animate and scrollTop methods in jQuery, you don’t need to use plug-ins to create simple scroll-to-top animations.

// Back to top

$('.top').click(function (e) {

 e.preventDefault();

 $('html, body').animate({scrollTop: 0}, 800);

});

<!-- Create an anchor tag -->

<a class="top" href="#">Back to top</a>

Copy after login

Change the position you want to scroll to by using the value of scrollTop. Essentially that's what you do: let the page scroll for the next 800 milliseconds until it scrolls to the top of the document.

Note: Let’s take a look at some of scrollTop’s naughty behaviors.

2. Image preloading

If your web page uses a lot of hidden image files (for example: images displayed on mouseover), then preloading of images makes sense:

$.preloadImages = function () {
 for (var i = 0; i < arguments.length; i++) {
 $('<img>').attr('src', arguments[i]);
 }
}; 
$.preloadImages('img/hover-on.png', 'img/hover-off.png');
Copy after login

3. Determine whether the image is loaded

Sometimes you may need to check whether the image has been loaded so that you can continue to execute the corresponding js code:

$('img').load(function () {
 console.log('image load successful');
});
Copy after login

You can also check if a specific image has been loaded and replaced by an tag with an Id or class.

4. Automatically repair damaged images

If you happen to find broken image links on your site, it can be a pain to replace them one by one. This simple code can save a lot of trouble:

$('img').on('error', function () {
 if(!$(this).hasClass('broken-image')) {
 $(this).prop('src', 'img/broken.png').addClass('broken-image');
 }
});
Copy after login

Even if you don’t have any broken links, adding this code will have no impact.

5. Hover switching class

Let’s say you want to change the visual effect of an element on your page when a user hovers over it. When the user mouses over an element, you can add a class to the element and remove the class when the mouse stops hovering:

$('.btn').hover(function () {
 $(this).addClass('hover');
}, function () {
 $(this).removeClass('hover');
});
Copy after login

If you want a simpler way to use the toggleClass method, just add the necessary CSS:

$('.btn').hover(function () {
 $(this).toggleClass('hover');
});
Copy after login

Note: CSS is a quick solution in this case, but it’s still worth knowing.

6. Disable input

Sometimes you may need to use a form's submit button or an input field until the user performs an action (for example: checking the "I have read the terms" checkbox). Set the disabled attribute on your input box, and then enable it when you need it:

Copy code The code is as follows:
$('input[type="submit"]').prop ('disabled', true);

All you need to do is run the prop method on the input box again, but set the disabled value to false:

Copy code The code is as follows:
$('input[type="submit"]').prop ('disabled', false);

7. Stop loading links

Sometimes you don't want to link to a specific web page or reload the page; you may want them to do something else, like trigger some other script. Here are tips to prevent breach of contract actions:

$('a.no-link').click(function (e) {
 e.preventDefault();
});
Copy after login

8. toggle fade/slide

Sliding and fade-in/fade-out are animations that we often use heavily in jQuery. You may only want to display an element when the user performs certain click events, in which case a fade in/out or sliding method is required. But if you need that element to appear when you click it for the first time and disappear when you click it for the second time, the code is as follows:

// Fade
$('.btn').click(function () {
 $('.element').fadeToggle('slow');
});
// Toggle
$('.btn').click(function () {
 $('.element').slideToggle('slow');
});
Copy after login

9. Simple accordion

Here’s a quick and easy way to create an accordion:

// Close all panels
$('#accordion').find('.content').hide();
// Accordion
$('#accordion').find('.accordion-header').click(function () {
 var next = $(this).next();
 next.slideToggle('fast');
 $('.content').not(next).slideUp('fast');
 return false;
});
Copy after login

通过添加这个脚本,你需要做的则是必要的HTML操作在你的页面上。

10、使两个DIV同等高度

有时你会想要两个DIV有相同的高度,无论他们都有什么内容:

复制代码 代码如下:
$('.div').css('min-height', $('.main-div').height());

这个例子设置了DIV的最小高度,这意味着它的高度只可以比这个设置的高度大而不能小。然而,一个更灵活的方法是循环的一组元素,并设置将最高元素的高度作为高度:

var $columns = $('.column');
var height = 0;
$columns.each(function () {
 if ($(this).height() > height) {
 height = $(this).height();
 }
});
$columns.height(height);
Copy after login

如果你想要所有的列有相同的高度:

var $rows = $('.same-height-columns');
$rows.each(function () {
 $(this).find('.column').height($(this).height());
});
Copy after login

11、在浏览器标签/新窗口打开外部链接

在新的浏览器标签或窗口中打开外部链接,并确保在同一个标签或窗口中打开的是同一个源的链接:

$('a[href^="http"]').attr('target', '_blank');
$('a[href^="//"]').attr('target', '_blank');
$('a[href^="' + window.location.origin + '"]').attr('target', '_self');
Copy after login

备注:window.location.origin 在IE10不工作。

12、根据文本获取元素

通过jQuery中的contains()选择器,你能找到一个元素内的文本内容。如果文本不存在,则这个元素将被隐藏:

var search = $('#search').val();
$('div:not(:contains("' + search + '"))').hide();
Copy after login

13、可见变化的触发

当用户不再聚焦或者重新聚焦一个标签时触发javascript脚本:

$(document).on('visibilitychange', function (e) {
 if (e.target.visibilityState === "visible") {
 console.log('Tab is now in view!');
 } else if (e.target.visibilityState === "hidden") {
 console.log('Tab is now hidden!');
 }
});
Copy after login

14、Ajax调用错误处理

当一个Ajax调用返回一个404或500的错误时,将执行该错误处理。如果该处理未定义,则其他jQuery代码便可能不会执行了。定义一个全局Ajax错误处理程序:

$(document).ajaxError(function (e, xhr, settings, error) {
 console.log(error);
});
Copy after login

15、链式操作

jQuery允许通过链式操作来减轻反复查询DOM和创建多个jQuery对象的过程。比如下面是你的方法调用:

$('#elem').show();
$('#elem').html('bla');
$('#elem').otherStuff();
Copy after login

这代码可以通过链式大大的提高:

$('#elem')
 .show()
 .html('bla')
 .otherStuff();
Copy after login

另一个方法是在一个可变的元素缓存($作为前置):

var $elem = $('#elem');
$elem.hide();
$elem.html('bla');
$elem.otherStuff();
Copy after login

链式和jQuery缓存方法是最好的做法,导致更短、更快的代码。

以上就是本文的全部内容,希望帮助大家提高jQuery应用能力。

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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Win11 Tips Sharing: Skip Microsoft Account Login with One Trick Win11 Tips Sharing: Skip Microsoft Account Login with One Trick Mar 27, 2024 pm 02:57 PM

Win11 Tips Sharing: One trick to skip Microsoft account login Windows 11 is the latest operating system launched by Microsoft, with a new design style and many practical functions. However, for some users, having to log in to their Microsoft account every time they boot up the system can be a bit annoying. If you are one of them, you might as well try the following tips, which will allow you to skip logging in with a Microsoft account and enter the desktop interface directly. First, we need to create a local account in the system to log in instead of a Microsoft account. The advantage of doing this is

What are the tips for novices to create forms? What are the tips for novices to create forms? Mar 21, 2024 am 09:11 AM

We often create and edit tables in excel, but as a novice who has just come into contact with the software, how to use excel to create tables is not as easy as it is for us. Below, we will conduct some drills on some steps of table creation that novices, that is, beginners, need to master. We hope it will be helpful to those in need. A sample form for beginners is shown below: Let’s see how to complete it! 1. There are two methods to create a new excel document. You can right-click the mouse on a blank location on the [Desktop] - [New] - [xls] file. You can also [Start]-[All Programs]-[Microsoft Office]-[Microsoft Excel 20**] 2. Double-click our new ex

A must-have for veterans: Tips and precautions for * and & in C language A must-have for veterans: Tips and precautions for * and & in C language Apr 04, 2024 am 08:21 AM

In C language, it represents a pointer, which stores the address of other variables; & represents the address operator, which returns the memory address of a variable. Tips for using pointers include defining pointers, dereferencing pointers, and ensuring that pointers point to valid addresses; tips for using address operators & include obtaining variable addresses, and returning the address of the first element of the array when obtaining the address of an array element. A practical example demonstrating the use of pointer and address operators to reverse a string.

VSCode Getting Started Guide: A must-read for beginners to quickly master usage skills! VSCode Getting Started Guide: A must-read for beginners to quickly master usage skills! Mar 26, 2024 am 08:21 AM

VSCode (Visual Studio Code) is an open source code editor developed by Microsoft. It has powerful functions and rich plug-in support, making it one of the preferred tools for developers. This article will provide an introductory guide for beginners to help them quickly master the skills of using VSCode. In this article, we will introduce how to install VSCode, basic editing operations, shortcut keys, plug-in installation, etc., and provide readers with specific code examples. 1. Install VSCode first, we need

PHP programming skills: How to jump to the web page within 3 seconds PHP programming skills: How to jump to the web page within 3 seconds Mar 24, 2024 am 09:18 AM

Title: PHP Programming Tips: How to Jump to a Web Page within 3 Seconds In web development, we often encounter situations where we need to automatically jump to another page within a certain period of time. This article will introduce how to use PHP to implement programming techniques to jump to a page within 3 seconds, and provide specific code examples. First of all, the basic principle of page jump is realized through the Location field in the HTTP response header. By setting this field, the browser can automatically jump to the specified page. Below is a simple example demonstrating how to use P

Win11 Tricks Revealed: How to Bypass Microsoft Account Login Win11 Tricks Revealed: How to Bypass Microsoft Account Login Mar 27, 2024 pm 07:57 PM

Win11 tricks revealed: How to bypass Microsoft account login Recently, Microsoft launched a new operating system Windows11, which has attracted widespread attention. Compared with previous versions, Windows 11 has made many new adjustments in terms of interface design and functional improvements, but it has also caused some controversy. The most eye-catching point is that it forces users to log in to the system with a Microsoft account. For some users, they may be more accustomed to logging in with a local account and are unwilling to bind their personal information to a Microsoft account.

Tips for using Laravel form classes: ways to improve efficiency Tips for using Laravel form classes: ways to improve efficiency Mar 11, 2024 pm 12:51 PM

Forms are an integral part of writing a website or application. Laravel, as a popular PHP framework, provides rich and powerful form classes, making form processing easier and more efficient. This article will introduce some tips on using Laravel form classes to help you improve development efficiency. The following explains in detail through specific code examples. Creating a form To create a form in Laravel, you first need to write the corresponding HTML form in the view. When working with forms, you can use Laravel

Detailed explanation of the usage skills of √ symbol in word box Detailed explanation of the usage skills of √ symbol in word box Mar 25, 2024 pm 10:30 PM

Detailed explanation of the tips for using the √ symbol in the Word box. In daily work and study, we often need to use Word for document editing and typesetting. Among them, the √ symbol is a common symbol, which usually means "right". Using the √ symbol in the Word box can help us present information more clearly and improve the professionalism and beauty of the document. Next, we will introduce in detail the skills of using the √ symbol in the Word box, hoping to help everyone. 1. Insert the √ symbol In Word, there are many ways to insert the √ symbol. one

See all articles