Home >Web Front-end >JS Tutorial >Share 15 jquery tips that everyone is familiar with_jquery
15 well-known jquery tips to help improve your jQuery application, share with everyone
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>
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');
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'); });
You can also check if a specific image has been loaded and replaced by an a1f02c36ba31691bcfe87b2722de723b 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'); } });
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'); });
If you want a simpler way to use the toggleClass method, just add the necessary CSS:
$('.btn').hover(function () { $(this).toggleClass('hover'); });
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:
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(); });
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'); });
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; });
通过添加这个脚本,你需要做的则是必要的HTML操作在你的页面上。
10、使两个DIV同等高度
有时你会想要两个DIV有相同的高度,无论他们都有什么内容:
var $columns = $('.column'); var height = 0; $columns.each(function () { if ($(this).height() > height) { height = $(this).height(); } }); $columns.height(height);
如果你想要所有的列有相同的高度:
var $rows = $('.same-height-columns'); $rows.each(function () { $(this).find('.column').height($(this).height()); });
11、在浏览器标签/新窗口打开外部链接
在新的浏览器标签或窗口中打开外部链接,并确保在同一个标签或窗口中打开的是同一个源的链接:
$('a[href^="http"]').attr('target', '_blank'); $('a[href^="//"]').attr('target', '_blank'); $('a[href^="' + window.location.origin + '"]').attr('target', '_self');
备注:window.location.origin 在IE10不工作。
12、根据文本获取元素
通过jQuery中的contains()选择器,你能找到一个元素内的文本内容。如果文本不存在,则这个元素将被隐藏:
var search = $('#search').val(); $('div:not(:contains("' + search + '"))').hide();
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!'); } });
14、Ajax调用错误处理
当一个Ajax调用返回一个404或500的错误时,将执行该错误处理。如果该处理未定义,则其他jQuery代码便可能不会执行了。定义一个全局Ajax错误处理程序:
$(document).ajaxError(function (e, xhr, settings, error) { console.log(error); });
15、链式操作
jQuery允许通过链式操作来减轻反复查询DOM和创建多个jQuery对象的过程。比如下面是你的方法调用:
$('#elem').show(); $('#elem').html('bla'); $('#elem').otherStuff();
这代码可以通过链式大大的提高:
$('#elem') .show() .html('bla') .otherStuff();
另一个方法是在一个可变的元素缓存($作为前置):
var $elem = $('#elem'); $elem.hide(); $elem.html('bla'); $elem.otherStuff();
链式和jQuery缓存方法是最好的做法,导致更短、更快的代码。
以上就是本文的全部内容,希望帮助大家提高jQuery应用能力。