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>
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 alt="Share 15 jquery tips that everyone is familiar with_jquery" >').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 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:
All you need to do is run the prop method on the input box again, but set the disabled value to 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(); });
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有相同的高度,无论他们都有什么内容:
这个例子设置了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应用能力。

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.