Home Web Front-end JS Tutorial jquery tips and jquery three abbreviations that everyone in WEB front-end development should know_jquery

jquery tips and jquery three abbreviations that everyone in WEB front-end development should know_jquery

May 16, 2016 pm 03:32 PM

A collection of simple tips to help you improve your jQuery skills. At present, the editor has compiled 14 jquery tips for you.

Directory structure

1 Back to top button
2 Preloaded images
3 Check whether the image is loaded
4 Automatically repair damaged pictures
Class switch on 5Hover
6Disable input field
7Stop link loading
8 fade/slide switch
9 simple folding effects
10Set two Divs to the same height
11Open external link in new window
12 Find the text element
13Switch visible and hidden triggers

The following will introduce to you the specific meaning of each tip.

1. Back to top button

By using the animate and scrollTop methods in jQuery, you can create a simple back to top animation without the need for a plugin:

 // Back to top
 $('a.top').click(function (e) {
 e.preventDefault();
 $(document.body).animate({scrollTop: 0}, 800);
 });
 <!-- Create an anchor tag -->
 <a class="top" href="#">Back to top</a>
Copy after login

Change the value of scrollTop to where you want the scrollbar to stop. And then what you do is, set it to go back to the top in 800 milliseconds.

2. Preload images

If your page uses a lot of images that are not initially visible (e.g. bound to hover), it is useful to preload them:

$.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. Check whether the image is loaded

Sometimes you may need to check whether the image is completely loaded before you can perform subsequent operations in the script:

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

You can also check whether a specific image has been loaded by replacing the img tag with an ID or class.

4. Automatically repair damaged pictures

If you find that the image links on your website are broken, it will be troublesome to replace them one by one. This simple code can help a lot:

 $('img').on('error', function () {
 $(this).prop('src', 'img/broken.png');
});
Copy after login

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

5. Class switching on Hover

If the user's mouse hovers over a clickable element on the page, you want to change the visual representation of this element. You can use the following code to add a class to the element when the user hovers it; remove the class when the user leaves the mouse:

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

You only need to add the necessary CSS. If you need a simpler way, you can also use the toggleClass method:

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

Note: CSS may be a faster solution for this example, but it’s still worth knowing.

6. Disable input field

Sometimes you may want to make a form's submit button or its text input box unavailable until the user performs a specific action (such as confirming the "I have read the terms" checkbox). Add disabled attribute to your input to achieve the effect you want:

 $('input[type="submit"]').prop('disabled', true);
Copy after login

When you want to change the value of disabled to false, just run the prop method on the input again.

 $('input[type="submit"]').prop('disabled', false);
Copy after login

7. Stop link loading

Sometimes you don’t want a link to jump to a page or reload the page, but want to be able to do something else, such as trigger other scripts. The following code is a little trick to disable the default behavior:

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

8. Fade/slide switch

Fade in and out and slide are animation effects that we often use jQuery to create. Maybe you just want to reveal an element when the user clicks on something, using fadeIn and slideDown are both great. But if you want the element to appear on the first click and disappear on the second click, the following code can do the job well:

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

Copy after login

9. Simple accordion effect

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

 // 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

After adding this script, all you need to do is see if the script works properly within the necessary HTML.

10. Make the two Divs the same height

Sometimes you might want two divs to have the same height, regardless of what content they contain:

('.div').css('min-height', $('.main-div').height());
Copy after login

This example sets min-height, meaning it can be larger than the main div, but never smaller. But a more flexible method is to iterate through the settings of a set of elements and set the height to the highest value in the element:

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

If you want all columns to be the same height:

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

11. Open external link in new tab/window

Open external links in a new tab or window, and make sure internal links open in the same tab or window:

 $('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 在 IE 10 中不可用,该 issue 的修复方法。

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

Ajax 调用的错误处理

当某次 Ajax 调用返回 404 或 500 错误,就会执行错误处理。但如果没有定义该处理,其他 jQuery 代码或许会停止工作。可以通过下面这段代码定义一个全局 Ajax 错误处理:

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

14.插件链式调用

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小技巧之三个简写

简洁写法如下所示:

对象的简写

在过去,如果你想创建一个对象,你需要这样:

var car = new Object(); 
car.colour = 'red'; 
car.wheels = 4; 
car.hubcaps = 'spinning'; 
car.age = 4;
Copy after login

下面的写法能够达到同样的效果:

var car = { 
colour:'red', 
wheels:4, 
hubcaps:'spinning', 
age:4 
}
Copy after login

这样就简单多了,你不需要反复使用这个对象的名称。
这样 car 就定义好了,也许你会遇到 invalidUserInSession 的问题,这只有你在使用IE时会碰到,只要记住一点,不要右大括号前面写分号,你就不会有麻烦。

数组的简写

传统的定义数组的方法是这样:

var moviesThatNeedBetterWriters = new Array(
  'Transformers','Transformers2','Avatar','Indiana Jones 4');
Copy after login

简写版是这样:

var moviesThatNeedBetterWriters = [
  'Transformers','Transformers2','Avatar','Indiana Jones 4']; 
Copy after login

对于数组,这里有个问题,其实没有什么图组功能。但你会经常发现有人这样定义上面的 car ,就像这样:

var car = new Array(); 
car['colour'] = 'red'; 
car['wheels'] = 4; 
car['hubcaps'] = 'spinning'; 
car['age'] = 4;
Copy after login

数组不是万能的;这样写不对,会让人困惑。图组实际上是对象的功能,人们混淆了这两个概念。

三元条件符号的简写

另外一个非常酷的简写方法是使用与三元条件符号。
你不必写成下面的样子:

var direction; 
if(x < 200){ 
  direction = 1; 
}
else { 
  direction = -1; 
}
Copy after login

你可以使用三元条件符号简化它:

var direction = x < 200 &#63; 1 : -1;
Copy after login

当条件为true 时取问号后面的值,否则取冒号后面的值。

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 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
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)

Replace String Characters in JavaScript Replace String Characters in JavaScript Mar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

10 Ways to Instantly Increase Your jQuery Performance 10 Ways to Instantly Increase Your jQuery Performance Mar 11, 2025 am 12:15 AM

This article outlines ten simple steps to significantly boost your script's performance. These techniques are straightforward and applicable to all skill levels. Stay Updated: Utilize a package manager like NPM with a bundler such as Vite to ensure

Using Passport With Sequelize and MySQL Using Passport With Sequelize and MySQL Mar 11, 2025 am 11:04 AM

Sequelize is a promise-based Node.js ORM. It can be used with PostgreSQL, MySQL, MariaDB, SQLite, and MSSQL. In this tutorial, we will be implementing authentication for users of a web app. And we will use Passport, the popular authentication middlew

How to Build a Simple jQuery Slider How to Build a Simple jQuery Slider Mar 11, 2025 am 12:19 AM

This article will guide you to create a simple picture carousel using the jQuery library. We will use the bxSlider library, which is built on jQuery and provides many configuration options to set up the carousel. Nowadays, picture carousel has become a must-have feature on the website - one picture is better than a thousand words! After deciding to use the picture carousel, the next question is how to create it. First, you need to collect high-quality, high-resolution pictures. Next, you need to create a picture carousel using HTML and some JavaScript code. There are many libraries on the web that can help you create carousels in different ways. We will use the open source bxSlider library. The bxSlider library supports responsive design, so the carousel built with this library can be adapted to any

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

See all articles