Jquery 3.6.0 released!

jQuery Slim build

Иногда вам не нужно делать ajax запросы, или вы предпочитаете использовать отдельные библиотеки для этих целей, например request,axios, или модуль $http в AngularJS. По этому вместе с стандартной сборкой jQuery, которая содержит под модули ajax, и анимационных эффектов, предоставляется урезанная ‘slim’ версия. В наше время размер библиотеки jQuery кажется крошечным по сравнению с другими фреймворками и библиотеками, но все же можно уменьшить нагрузку на сервер используя slim сборку, которая весит всего 6kb при использовании gzip сжатия, обычная версия весит 24 килобайта.

https://code.jquery.com/jquery-3.3.1.slim.js https://code.jquery.com/jquery-3.3.1.slim.min.js

Изменения в jQuery 3.3.0

Теперь методы .addClass(), .removeClass(), и .toggleClass() принимают как параметр массив классов.

jQuery(‘section.main’).addClass();

Изменения в jQuery 3.2.0

Добавлена поддержка кастомных CSS свойств

<div style="--margin: 10px; margin: var(--margin)">
Some content
</div> 
<script>
$('div').css('--margin') ; // should return 10
$('div').css('--margin',20') ; // should change block margin to 20
</script>
  • Методы jQuery.holdReady,jQuery.nodeName,jQuery.isArray стали deprecated
  • Исправлена ошибка в методах .width(), .height() и других связанных методах где учитывались CSS transforms свойства. Например, елемент со стилем transform: scale(3x) не должен иметь высоту и ширину в три раза больше.
  • Добавлена поддержка элемента <template> в методе .contents().
let deferred = jQuery.Deferred();
deferred.then(function() {
console.log("first promise");
throw new Error("Some error occured");
})
.then(function() {
console.log("second promise");
}, function(err) {
console.log("rejection promise", err instanceof Error);
});
deferred.resolve();

Изменения в jQuery 3.0

jQuery.Deferred теперь совместим с Promises/A+

Объекты класса jQuery.Deferred теперь совместимы с Promises/A+ и промисами ES2015. Всем кто использовал этот метод ранее, нужно будет внести изменения, или заменить его на метод pipe. Также исключение выброшено в колбек .then() теперь становится значением reject. Все объекты deferred которые базировались на то что будет выброшено исключения никогда не будут выполены (resolved).

Раньше первый промис выполнялся и далее выбрасывалось исключения, и дальнейшее выполнение прекращалось. Связи с требованиями стандарта, выполняются все три колбека.

Колбеки будут выполняться асинхронно, не смотря на то Deferred был resolved

let defer = jQuery.Deferred();
defer.resolve();
defer.then(function() {
    console.log("success message");
});
console.log("after message");

Раньше в консоль бы вывелось «success message» потом «after message», а в последней версии наоборот.

К Deferred был добавлен метод catch()

Анимации теперь используют requestAnimationFrame В браузерах что поддерживают requestAnimationFrame будет использоваться это API для управления анимациями. Что уменьшит использование ресурсов CPU и увеличит время работы батареи на мобильных устройствах

  • Увеличена производительность кастомных селекторов.
  • Для некоторых селектора например таких как :visible скорость работы была увеличена в 17 раз

Просмотры:
9 005

 

Download

You can get the files from the jQuery CDN, or link to them directly:

You can also get this release from npm:

Slim build

Sometimes you don’t need ajax, or you prefer to use one of the many standalone libraries that focus on ajax requests. And often it is simpler to use a combination of CSS and class manipulation for web animations. Along with the regular version of jQuery that includes the ajax and effects modules, we’ve released a “slim” version that excludes these modules. The size of jQuery is very rarely a load performance concern these days, but the slim build is about 6k gzipped bytes smaller than the regular version. These files are also available in the npm package and on the CDN:

These updates are already available as the current versions on npm and Bower. Information on all the ways to get jQuery is available at https://jquery.com/download/. Public CDNs receive their copies today, please give them a few days to post the files. If you’re anxious to get a quick start, use the files on our CDN until they have a chance to update.

link About the Code

jQuery is provided under the MIT license.

The code is hosted and developed in the jQuery GitHub repository. If you’ve spotted some areas of code that could be improved, please feel free to discuss it on the Developing jQuery Core Forum. If you’d like to participate in developing jQuery, peruse our contributor site for more information.

To find and download plugins developed by jQuery contributors, please visit the Plugins site. Plugin authors are responsible for maintenance of their plugins. Feedback on plugins should be directed to the plugin author, not the jQuery team.

Build from Git

Note: To just use the latest work-in-progress version of jQuery, please try the jQuery Pre-Release Build described above.

All source code is kept under Git revision control, which you can browse online. The repository’s README has more information on building and testing your own jQuery, as well as instructions on creating a custom build that excludes some APIs to reduce file size.

If you have access to Git, you can connect to the repository here:

1

You can also check out and build a specific version of jQuery from GitHub:

1

2

The README file for a specific version will have instructions for building that version, as the process has changed over time.

Download

You can get the files from the jQuery CDN, or link to them directly:

You can also get this release from npm:

Slim build

Sometimes you don’t need ajax, or you prefer to use one of the many standalone libraries that focus on ajax requests. And often it is simpler to use a combination of CSS and class manipulation for web animations. Along with the regular version of jQuery that includes the ajax and effects modules, we’ve released a “slim” version that excludes these modules. The size of jQuery is very rarely a load performance concern these days, but the slim build is about 6k gzipped bytes smaller than the regular version. These files are also available in the npm package and on the CDN:

These updates are already available as the current versions on npm and Bower. Information on all the ways to get jQuery is available at https://jquery.com/download/. Public CDNs receive their copies today, please give them a few days to post the files. If you’re anxious to get a quick start, use the files on our CDN until they have a chance to update.

jQuery Core — All 3.x Versions

  • jQuery Core 3.6.0 — uncompressed, minified, slim, slim minified
  • jQuery Core 3.5.1 — uncompressed, minified, slim, slim minified
  • jQuery Core 3.5.0 — uncompressed, minified, slim, slim minified
  • jQuery Core 3.4.1 — uncompressed, minified, slim, slim minified
  • jQuery Core 3.4.0 — uncompressed, minified, slim, slim minified
  • jQuery Core 3.3.1 — uncompressed, minified, slim, slim minified
  • jQuery Core 3.3.0 — uncompressed, minified, slim, slim minified
  • jQuery Core 3.2.1 — uncompressed, minified, slim, slim minified
  • jQuery Core 3.2.0 — uncompressed, minified, slim, slim minified
  • jQuery Core 3.1.1 — uncompressed, minified, slim, slim minified
  • jQuery Core 3.1.0 — uncompressed, minified, slim, slim minified
  • jQuery Core 3.0.0 — uncompressed, minified, slim, slim minified

Обращение к элементам в jQuery

Для того чтобы писать код на jQuery, вам понадобится использовать знак $, который является псевдонимом (или сокращением) для идентификатора на jQuery. Например, чтобы выбрать все и добавить css-свойство с помощью jQuery, а также поменять класс при клике на этом блоке, необходимо написать такой код:

Простой скрипт на jQuery

<style>
.jq-test { padding: 10px; background: #90c4f8; }
</style>

<div class=»jq-test»>
<h5>Test Block 1</h5>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Distinctio necessitatibus commodi
dolorem natus qui ut suscipit, inventore expedita explicabo, ipsa.</p>
</div>
<div class=»jq-test»>
<h5>Test Block 2</h5>
<p>Facilis veniam praesentium modi possimus repudiandae eaque error eum provident similique
debitis eligendi, laudantium incidunt earum sed ea dicta reprehenderit.</p>
</div>
<div class=»jq-test»>
<h5>Test Block 3</h5>
<p>Ratione possimus ullam dolor fugiat facilis! Eum iusto architecto laudantium ex molestiae commodi,
sed earum nesciunt ut saepe deleniti ea.</p>
</div>
<div class=»jq-test»>
<h5>Test Block 4</h5>
<p>Quibusdam, tempore sapiente distinctio laboriosam explicabo totam deleniti, aliquam consectetur,
ullam dolore non laudantium doloribus. Aperiam alias accusantium iusto quas.</p>
</div>

<script>
$(document).ready(function(){
$(‘.jq-test’).css(‘border-bottom’, ‘5px double #cde’);
$(‘.jq-test’).click(function(){
$(this).toggleClass(«jq-test»);
});
});
</script>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

<style>

.jq-test {padding10px;background#90c4f8;}

</style>
 

<div class=»jq-test»>

<h5>Test Block1<h5>

<p>Lorem ipsum dolor sit amet,consectetur adipisicing elit.Distinctio necessitatibus commodi

dolorem natus qui ut suscipit,inventore expedita explicabo,ipsa.<p>

<div>

<div class=»jq-test»>

<h5>Test Block2<h5>

<p>Facilis veniam praesentium modi possimus repudiandae eaque error eum provident similique

debitis eligendi,laudantium incidunt earum sed ea dicta reprehenderit.<p>

<div>

<div class=»jq-test»>

<h5>Test Block3<h5>

<p>Ratione possimus ullam dolor fugiat facilis!Eum iusto architecto laudantium ex molestiae commodi,

sed earum nesciunt ut saepe deleniti ea.<p>

<div>

<div class=»jq-test»>

<h5>Test Block4<h5>

<p>Quibusdam,tempore sapiente distinctio laboriosam explicabo totam deleniti,aliquam consectetur,

ullam dolore non laudantium doloribus.Aperiam alias accusantium iusto quas.<p>

<div>

 
<script>

$(document).ready(function(){

$(‘.jq-test’).css(‘border-bottom’,’5px double #cde’);

$(‘.jq-test’).click(function(){

$(this).toggleClass(«jq-test»);

});

});

</script>

Код несложный, он добавляет рамку внизу блока. Клик на голубом блоке удаляет/добавляет класс «jq-test» к нему с помощью метода jQuery .

Test Block 1

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Distinctio necessitatibus commodi dolorem natus qui ut suscipit, inventore expedita explicabo, ipsa.

Test Block 2

Facilis veniam praesentium modi possimus repudiandae eaque error eum provident similique debitis eligendi, laudantium incidunt earum sed ea dicta reprehenderit.

Test Block 3

Ratione possimus ullam dolor fugiat facilis! Eum iusto architecto laudantium ex molestiae commodi, sed earum nesciunt ut saepe deleniti ea.

Test Block 4

Quibusdam, tempore sapiente distinctio laboriosam explicabo totam deleniti, aliquam consectetur, ullam dolore non laudantium doloribus. Aperiam alias accusantium iusto quas.

Просмотров:
890

Правила работы с библиотекой jQuery

1. Как добавить jQuery на веб-страницу

Добавить библиотеку jQuery на свою веб-страницу можно двумя способами:

Использовать версию файла jQuery, размещенную на ресурсах , Microsoft или jQuery.com.
Данный метод использует «Сеть дистрибуции контента» (CDN, content distribution network), т.е. файл jQuery расположен на другом веб-сайте, который при запросе пользователем отправляет данный файл на его компьютер. Очевидные преимущества данного способа — снижение нагрузки на собственный веб-сервер и ускорение загрузки файла в силу разветвленности сети серверов дистрибьютора.

Чтобы воспользоваться данным способом, необходимо перейти по одной из ссылок:CDNJS CDN
После перехода на сайт ресурса вам потребуется всего лишь скопировать ссылку на jQuery-файл и добавить её на свою веб-страницу между тегами <script>...</script>. В результате у вас должно получиться, например,

Загрузить последнюю версию библиотеки jQuery с официального сайта. Для этого вам необходимо перейти по адресу jQuery.com и выбрать интересующую вас версию библиотеки. Для загрузки предлагается две версии jQuery-файла — минимизированный и несжатый. Размер несжатого файла около 300 Кб, он содержит комментарии, поэтому его лучше использовать с целью разработки и отладки кода.
Минимизированная версия файла весит около 100Кб, в ней удалены все комментарии и ненужные пробелы, что ускоряет загрузку файла браузером.

2. Правила добавления jQuery на страницу

Размещайте ссылки на jQuery-файл внутри тега <head>.Размещайте ссылки на jQuery-файл после ссылок на стили CSS, так как зачастую библиотека jQuery производит манипуляции со стилями элементов веб-страницы.Размещайте другие теги <script>...</script> только после ссылки на файл jQuery, если данный скрипт использует библиотеку jQuery.

3. Как создать новый html-элемент

Создать пустой html-элемент, например, блок, можно несколькими способами:

1) с помощью краткой формы записи $("<div>")
2) с помощью инструкции $("<div></div>")
3) с помощью инструкции $("<div/>")

Все три способа рабочие, но, тем не менее, рекомендуется включать открывающие и закрывающие теги, чтобы показать, что данный элемент может содержать другие элементы.

При создании нового элемента методу $() можно передать второй параметр в виде объекта JavaScript, определяющий дополнительные атрибуты элемента:

Таким образом создается элемент <img> с заданными атрибутами и включается в дерево DOM.

Build a custom set of Tools.

Or download the source code

Here you can download individual tools or create a custom
combination of tools by selecting only those you want. Both
the source code and the minified
versions are available.

Include jQuery

jQuery

All tools depend on this library (except flashembed). Can alternatively be included from googleapis (see below)

UI Tools

Tabs

6761.0

The most important UI tool

Slideshow plugin

3678.0

Transforms tabs into a working slideshow

Tooltip

7832.0

The basics of UI design

Slide effect

1687.0

A sliding tooltip effect with customized sliding directions, dimensions and speeds

Dynamic plugin

3914.0

Dynamic positioning of the tooltip so that it always stays in the viewport

Overlay

6455.0

A generic HTML overlaying widget

Apple effect

3281.0

An overlay effect that you might have seen on apple.com

Form Tools

Dateinput

17850.0

HTML5 date input for humans

Rangeinput

10653.0

HTML5 range input for humans

Validator

14803.0

HTML5 input validation for humans

Flashembed

6773.0

The future of Flash embedding. Works as a standalone tool and jQuery is not required.

History

2193.0

Back button for AJAX apps

Expose

4497.0

Makes your HTML stand out from its surroundings

Mousewheel

1601.0

Эффекты jQuery

Эффекты jQuery часто работают вместе с событиями и позволяют добавлять анимацию и иным образом управлять элементами на странице.

Для примера создайте наплывающий элемент, который можно закрывать и открывать. Для этого можно использовать два ID (один, чтобы открыть, а второй – чтобы закрыть элемент). Но мы используем для этого класс.

Удалите теги <button> и <p> из тела файла index.html, затем добавьте в документ HTML:

В файле style.css используйте CSS, чтобы спрятать элемент overlay с помощью display: none и поместить его в центре экрана.

Вернитесь в файл scripts.js и используйте метод toggle(), который будет включать и отключать свойство CSS display (переключать none и block), скрывая и отображая наплывающий элемент при клике.

Обновите index.html. Теперь вы можете управлять наплывающим элементом, кликая по кнопкам. Вместо toggle() вы можете использовать другие встроенные элементы jQuery, например, fadeToggle() или slideToggle().

Вот краткий список популярных эффектов:

  • toggle(): управляет видимостью элемента; с ним связаны эффекты show() и hide().
  • fadeToggle(): управляет видимостью элемента с помощью прозрачности/непрозрачности; к нему относятся эффекты fadeIn() и fadeOut().
  • slideToggle(): управляет видимостью элемента с помощью эффекта скольжения; с ним связаны slideDown() и slideUp().
  • animate(): пользовательские эффекты анимации.

События jQuery прослушивают взаимодействие пользователя с сайтом, а эффекты jQuery управляют элементами, если указанное действие происходит.

CSSHTMLJavascriptjQuery

Подключаем jQuery

Для того чтобы добавить jQuery на страницу, необходимо расположить тег с атрибутом , в котором указывается путь к скачанному файлу с jquery.min.js. Например, разместите следующий код в секции или до основного скрипта:

Подключаем jQuery и свой скрипт

JavaScript

<script src=»папка_со_скриптами/jquery.min.js»></script>
<script src=»папка_со_скриптами/myscript.js»></script>

//Очень часто это такой путь:
<script src=»js/jquery-3.5.0.min.js»></script>
<script src=»js/myscript.js»></script>

1
2
3
4
5
6

<script src=»папка_со_скриптами/jquery.min.js»></script>

<script src=»папка_со_скриптами/myscript.js»></script>

 
//Очень часто это такой путь:

<script src=»js/jquery-3.5.0.min.js»></script>

<script src=»js/myscript.js»></script>

Подключение jQuery из локальной папки имеет следующие плюсы:

  1. Вы используете ту версию, которую считаете для сюда удобной
  2. Вы в любой момент можете найти файл с jQuery в папке и подключить его к другому сайту/html-странице.
  3. Вы не зависите от наличия/отсутствия интернета для того, чтобы написать свой код.

В том случае, когда у вас есть сайт в сети или вы уверены в стабильности своего интернета, вам стоит воспользоваться онлайн-сервисами, которые позволяют подключить jQuery из сети распределенного контента (CDN). Плюсы этого способа:

  1. Таких сервисов очень много, и они позволяют загрузить jQuery с ближайшего источника,
  2. Вы можете выбрать версию jQuery, хотя для этого вам, возможно, придется поискать нужную.
  3. Пользователь, просматривающий ваш сайт, уже загрузил в кэш своего браузера jQuery с того источника, который используете вы, и ваш сайт подхватит ее из кэша браузера, а значит загрузка будет очень быстрой.

jQuery UI 1.8

uncompressedminified

Themes

baseblack-tieblitzercupertinodark-hivedot-luveggplantexcite-bikeflickhot-sneakshumanityle-frogmint-chocovercastpepper-grinderredmondsmoothnesssouth-streetstartsunnyswanky-pursetrontasticui-darknessui-lightnessvader

Previous Releases

  • jQuery UI 1.8.23 — uncompressed, minified, theme
  • jQuery UI 1.8.22 — uncompressed, minified, theme
  • jQuery UI 1.8.21 — uncompressed, minified, theme
  • jQuery UI 1.8.20 — uncompressed, minified, theme
  • jQuery UI 1.8.19 — uncompressed, minified, theme
  • jQuery UI 1.8.18 — uncompressed, minified, theme
  • jQuery UI 1.8.17 — uncompressed, minified, theme
  • jQuery UI 1.8.16 — uncompressed, minified, theme
  • jQuery UI 1.8.15 — uncompressed, minified, theme
  • jQuery UI 1.8.14 — uncompressed, minified, theme
  • jQuery UI 1.8.13 — uncompressed, minified, theme
  • jQuery UI 1.8.12 — uncompressed, minified, theme
  • jQuery UI 1.8.11 — uncompressed, minified, theme
  • jQuery UI 1.8.10 — uncompressed, minified, theme
  • jQuery UI 1.8.9 — uncompressed, minified, theme
  • jQuery UI 1.8.8 — uncompressed, minified, theme
  • jQuery UI 1.8.7 — uncompressed, minified, theme
  • jQuery UI 1.8.6 — uncompressed, minified, theme
  • jQuery UI 1.8.5 — uncompressed, minified, theme
  • jQuery UI 1.8.4 — uncompressed, minified, theme
  • jQuery UI 1.8.3 — uncompressed, minified, theme
  • jQuery UI 1.8.2 — uncompressed, minified, theme
  • jQuery UI 1.8.1 — uncompressed, minified, theme
  • jQuery UI 1.8.0 — uncompressed, minified, theme

Test Suite Convenience Methods Reference (See test/data/testinit.js)

q( ... );

Example:

q("main", "foo", "bar");

=>  div#main, span#foo, input#bar 
t( testName, selector,  "array", "of", "ids"  );

Example:

t("Check for something", "//", "foo", "bar");
fireNative( node, eventType )

Example:

fireNative( jQuery("#elem"), "click" );

Add random number to url to stop caching

url( "some/url" );

Example:

url("index.html");

=> "data/index.html?10538358428943"


url("mock.php?foo=bar");

=> "data/mock.php?foo=bar&10538358345554"

Run tests in an iframe

Some tests may require a document other than the standard test fixture, and
these can be run in a separate iframe. The actual test code and assertions
remain in jQuery’s main test files; only the minimal test fixture markup
and setup code should be placed in the iframe file.

testIframe( testName, fileName,
  function testCallback(
      assert, jQuery, window, document,
	   additional args  ) {
	...
  } );

This loads a page, constructing a url with fileName .
The iframed page determines when the callback occurs in the test by
including the «/test/data/iframeTest.js» script and calling
when appropriate. Often this
will be after either document ready or fires.

The receives the QUnit object created by
for this test, followed by the global , , and from
the iframe. If the iframe code passes any arguments to ,
they follow the argument.

Что такое jQuery и её поддержка браузерами

jQuery — это быстрая, лёгкая и многофункциональная JavaScript библиотека, основанная на принципе «пиши меньше, делай больше».

Её создал Джон Резиг в начале 2006 года. В настоящее время jQuery разрабатывается и поддерживается распределенной группой разработчиков как проект с открытым исходным кодом.

Сейчас последней версией jQuery является 3.5.1. Она поддерживается во всех основных браузерах: Chrome, Firefox, Safari, Edge, Opera и Internet Explorer 9+.

Преимущества и недостатки jQuery

Преимущества, которые даёт нам библиотеки jQuery при её использовании для написания клиентских сценариев:

  • компактность кода. Позволяет писать код более компактно чем на чистом javaScript, т.е. за гораздо меньшее количество строк кода.
  • простой и понятный синтаксис. Значительно упрощает написание многих вещей, например, таких как манипулирование DOM элементами, обработку событий, добавление эффектов анимации на страницу, AJAX запросов и т.д.
  • кроссбраузерность. Код написанный на jQuery будет гарантированно работать во всех основных браузерах. В то время как код, написанный на чистом JavaScript надо будет однозначно проверять во всех браузерах. Т.к. некоторые фрагменты кода могут не поддерживаться и их реализацию для этих браузеров нужно будет выполнять как-то по-другому, или например, использовать полифиллы.
  • открытый код. Библиотека jQuery является полностью бесплатной как для личных, так и для коммерческих проектов.

Кроме преимуществ, приведённых выше, у библиотеки jQuery имеются конечно и недостатки.

К недостаткам jQuery можно отнести то, что она может немного увеличивать скорость загрузки веб-страницы (её сжатый размер составляет около 30КБ), а также немного снижать производительность выполнения кода, чем если он был бы написан на чистом JavaScript.

Статистика использования jQuery

Если перейти к статистике, то многие крупные компании, используют jQuery в своих приложениях и сайтах. При этом растущий тренд продолжается, несмотря на очень горячие дискуссии в ИТ сообществах на тему: «Стоит ли использовать jQuery или нет в 2021 году?»

Статистика использования jQuery 10k крупнейшими сайтами:

Custom rich user experience — jquery.fileDownload.js & jQuery UI Dialog

File Name Description
Report0.pdf This file download will succeed
Report1.pdf This file download will fail
Report2.pdf This file download will succeed
Report3.pdf This file download will fail
Report4.pdf This file download will succeed

Toggle Source

        //Custom rich user experience - jquery.fileDownload.js & jQuery UI Dialog
        //uses the optional "options" argument
        //
        //      the below uses jQuery "on" http://api.jquery.com/on/ (jQuery 1.7 + required, otherwise use "delegate" or "live") so that any 
        //      <a class="fileDownload..."/> that is ever loaded into an Ajax site will automatically use jquery.fileDownload.js
        //      if you are using "on":
        //          you should generally be able to reduce the scope of the selector below "document" but it is used in this example so it
        //          works for possible dynamic manipulation in the entire DOM
        //
        $(function () {
            $(document).on("click", "a.fileDownloadCustomRichExperience", function () {

                var $preparingFileModal = $("#preparing-file-modal");

                $preparingFileModal.dialog({ modal: true });

                $.fileDownload($(this).prop('href'), {
                    successCallback: function (url) {

                        $preparingFileModal.dialog('close');
                    },
                    failCallback: function (responseHtml, url) {

                        $preparingFileModal.dialog('close');
                        $("#error-modal").dialog({ modal: true });
                    }
                });
                return false; //this is critical to stop the click event which will trigger a normal file download!
            });
        });
    
        
            We are preparing your report, please wait...

            
        

        
            There was a problem generating your report, please try again.
        
    

Security Fix

The main change in this release is a security fix, and it’s possible you will need to change your own code to adapt. Here’s why: jQuery used a regex in its method to ensure that all closing tags were XHTML-compliant when passed to methods. For example, this prefilter ensured that a call like is actually converted to . Recently, an issue was reported that demonstrated the regex could introduce a cross-site scripting (XSS) vulnerability.

The HTML parser in jQuery <=3.4.1 usually did the right thing, but there were edge cases where parsing would have unintended consequences. The jQuery team agreed it was necessary to fix this in a minor release, even though some code relies on the previous behavior and may break. The function does not use a regex in 3.5.0 and passes the string through unchanged.

If you absolutely need the old behavior, using the latest version of the jQuery migrate plugin provides a function to restore the old . After including the plugin you can call and jQuery will again ensure XHTML-compliant closing tags.

However, to sanitize user input properly, we also recommend using dompurify with the option to sanitize HTML from a user. If you don’t need the old behavior, but would still like to sanitize HTML from a user, dompurify should be used without the option, starting in jQuery 3.5.0. For more details, please see the 3.5 Upgrade Guide.

Essential Git

As the source code is handled by the Git version control system, it’s useful to know some features used.

Cleaning

If you want to purge your working directory back to the status of upstream, the following commands can be used (remember everything you’ve worked on is gone after these):

git reset --hard upstream/main
git clean -fdx

Rebasing

For feature/topic branches, you should always use the flag to , or if you are usually handling many temporary «to be in a github pull request» branches, run the following to automate this:

git config branch.autosetuprebase local

(see for more information)

Handling merge conflicts

If you’re getting merge conflicts when merging, instead of editing the conflicted files manually, you can use the feature
. Even though the default tool looks awful/old, it’s rather useful.

The following are some commands that can be used there:

  • — automerge as much as possible
  • — jump to next merge conflict
  • — change the order of the conflicted lines
  • — undo a merge
  • — mark a block to be the winner
  • — mark a line to be the winner
  • — save
  • — quit

Fixes

One bug worth highlighting is a bug we fixed in the Ajax script transport. jQuery used to evaluate any response to a request for a script as a script, which is not always the desired behavior. This is different than other data types where such a convention was fine (e.g. in the case of JSON). jQuery 3.5.0 will now only evaluate successful HTTP responses.

Other bug fixes and improvements include performance improvements in Sizzle, support for massive arrays in jQuery.map, using the native method where supported, a fix for syntax errors in the AMD modules, several improvements to our testing infrastructure, and more. You’ll find the full changelog below.

Custom use with Promises — jquery.fileDownload.js

File Name Description
Report0.pdf This file download will succeed
Report1.pdf This file download will fail
Report2.pdf This file download will succeed
Report3.pdf This file download will fail
Report4.pdf This file download will succeed

Toggle Source

        //
        //With jquery.fileDownload.js
        //custom use with promises
        //
        $(document).on("click", "a.fileDownloadPromise", function () {
            $.fileDownload($(this).prop('href'))
                .done(function () { alert('File download a success!'); })
                .fail(function () { alert('File download failed!'); });

            return false; //this is critical to stop the click event which will trigger a normal file download
        });
    

jQuery и AJAX

jQuery('div#intro').load('/some/fragment.html');
jQuery.get('/some/script.php', {'name': 'Simon'}, function(data) {
    alert('Сервер ответил: ' + data);
}); // GET-запрос к /some/script.php?name=Simon

jQuery.post('/some/script.php', {'name': 'Simon'}, function(data) {
    alert('Сервер ответил: ' + data);
}); // POST-запрос к /some/script.php

jQuery.getJSON('/some.json', function(json) {
    alert('JSON выдал: ' + json.foo + ' ' + json.bar);
}); // Возвращает и преобразует ответ от /some.json как JSON

jQuery.getScript('/script.js'); // GET-запрос к /script.js и eval()
Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector