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

Detailed explanation of the difference between using on instead of delegate and live in jQuery

黄舟
Release: 2017-06-26 10:04:22
Original
1208 people have browsed it

In the early days, when assigning events or values ​​to dynamic elements loaded later on the page, live was used. Due to the low efficiency (in fact, there is not much data and it cannot be felt) ), later the delegate is used instead, and later, after 1.7, on is used instead of delegate. Both live and delegate can still be used in the new version. They are different in writing. It is easy to get confused if you don’t write for a while, so write it down Memo. If you click any button in p to add a new button:


## Page:

<div id="panel">   
      <input type="button" name="name"  value="clone"class="btnAdd" />
</div>
Copy after login

Script:

##1.1 Using live

jQuery

Version 1.3+

1.2 Directly change live to on without giving a scope such as #panel. This is effective for the

button at the beginning of the page. In other words, cannot be directly replaced like this live

$(&#39;.btnAdd&#39;).on(&#39;click&#39;, function () {    
$(this).clone().appendTo(&#39;#panel&#39;);
});
Copy after login


2. To use delegate, you need to give it a range, such as #panel, and let it search inside. This works Achieve the same effect as live.


jQuery version 1.4.3+

$(&#39;#panel&#39;).delegate(&#39;.btnAdd&#39;, &#39;click&#39;, function () {
    $(this).clone().appendTo(&#39;#panel&#39;);
});
Copy after login

3.使用on 给它一个范围才行,如#panel,让它到里面找. 这样可以实现live和delegate一样的效果.

里面的'click', '.btnAdd'跟上面的delegate是相反的.只要记住on click是挨在一起的就行了.

jQuery版本1.7+

$(&#39;#panel&#39;).on(&#39;click&#39;, &#39;.btnAdd&#39;, function () {
    $(this).clone().appendTo(&#39;#panel&#39;);
});
Copy after login

The above is the detailed content of Detailed explanation of the difference between using on instead of delegate and live in jQuery. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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