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

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

WBOY
Release: 2016-05-16 15:32:23
Original
1717 people have browsed it

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 时取问号后面的值,否则取冒号后面的值。

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