Home >Web Front-end >JS Tutorial >jQuery's delegate_jquery thought of hiding divs by clicking elsewhere on the page

jQuery's delegate_jquery thought of hiding divs by clicking elsewhere on the page

WBOY
WBOYOriginal
2016-05-16 17:24:041174browse

Let’s start with the simplest one. If the page has a div with an id of test, we need to hide the div by clicking elsewhere on the page:

Copy code The code is as follows:



                                                              
There are generally two ways of thinking about this problem. Both of them will use the principle of event bubbling. If you want to learn more about the Javascript event mechanism, you can take a look at
JavaScript and HTML Interaction - Events, which It is not the focus of this article, so here is just a brief introduction to event bubbling,

Event bubbling

IE's event bubbling: the event is initially received by the most specific element, and then propagates upwards to less specific elements

Netscape's event capture: less specific nodes receive events earlier, while the most specific elements receive events last, contrary to event bubbling

DOM event flow: DOM level 2 events stipulate that the event flow includes three stages, the event capture stage, which is in the target stage, and the event bubbling stage. The first thing that happens is the event capture, which provides an opportunity to intercept the event, and then the actual target receives the event. , and finally the bubble sentence stage.

Opera, Firefox, Chrome, and Safari all support DOM event streaming. IE does not support event streaming and only supports event bubbling

If there is the following html, click on the div area, and the click event triggering sequence of different model event elements is as follows:

< html>


Test Page< /title><br></head><br><body><br>  <div><br>   Click Here</div><br></body><br></html> <br><br><br><br> </div> <br><br>When an event on the DOM is triggered, an event object event is generated. This object contains all information related to the event, including The element that generated the event, event type and other related information. All browsers support event objects, but in different ways. The event object has a method (W3C: stopPropagation)/property (IE: cancelBulle=true) that can prevent the event from continuing to bubble or capture. If we want to prevent bubbling when an event bubbles up to an element, we can write a browser-compatible method like this: <img src="http://files.jb51.net/file_images/article/201304/201304120922134.png" alt="jQuery's delegate_jquery thought of hiding divs by clicking elsewhere on the page" > <br><br><p></p> <div class="codetitle">Copy code<span><a style="CURSOR: pointer" data="84280" class="copybut" id="copybut84280" onclick="doCopy('code84280')"><u> The code is as follows:</u></a></span>function stopPropagation(e) {//Pass the event object Enter</div> if (e.stopPropagation) //Support W3C standard<div class="codebody" id="code84280"> e.stopPropagation();<br> else //IE8 and below browsers<br> e.cancelBubble = true;<br> }<br><br><br> <br>Because all browsers support event bubbling, and considering browser compatibility, we generally use event bubbling instead of event capturing when binding events. After understanding this, we can look at the following two ideas. </div> Idea 1<p>The first idea is divided into two steps</p> <p>Step one: Bind an event handler to the document's click event to hide the div<br> </p>Step 2: Bind an event handler to the click event of the div to prevent the event from bubbling to the document, and calling the onclick method of the document hides the div. <p> </p> <p></p> <p></p> <div class="codetitle">Copy code<span><a style="CURSOR: pointer" data="23801" class="copybut" id="copybut23801" onclick="doCopy('code23801')"><u> The code is as follows:</u><div class="codebody" id="code23801"> <br><script type="text/javascript"><br> function stopPropagation(e) {<br> if (e.stopPropagation) <br> e.stopPropagation();<br> else <br>                 e.cancelBubble = true; <br>                 $(document)                                                                                                                                   ;                                                                                                                                                                     <p> <br>In this way, when a non-div area of ​​the page is clicked, the onclick method of the document will be called directly or layer by layer to hide the div. When a div or its sub-elements are clicked, the event will always bubble up to the div itself. This At this time, the event will be prevented from continuing to bubble up, and the onclick method of the document will not be called, causing the div to be hidden, thus fulfilling our needs. <br> </p> <p>Idea 2<br><br> <br>We mentioned before that when an event on the DOM is triggered, an event object event will be generated. This object contains all information related to the event, including the element that generated the event, the event type and other related information. The first idea The parameter passed in by the click event handler of the div is this event object. There are several different ways to access the event object in IE, depending on how you specify the event handler. When adding event handlers directly to DOM elements, the event object exists as a property of the window object. <br> </p> </div>The event object contains an important attribute: target(W3C)/srcElement(IE). This attribute identifies the original element that triggered the event. The second idea is to use this attribute. We can directly bind an event handler to the click event of the document, and determine in the event handler whether the event source is the div element with id==test or its sub-element. If so, the method return does not perform any operation. If not, the event is hidden. div. <p></p> <p><strong></strong>Copy code</p> <p></p> The code is as follows:<p></p> <p><script type="text/javascript"> </p> <div class="codetitle">                                                                                                                                                                                                 .srcElement;<span>                                                                                                                                                                                                                                                                                             . <a style="CURSOR: pointer" data="5239" class="copybut" id="copybut5239" onclick="doCopy('code5239')">                                                                                                                                       <u>                                                                                                                                                                                          🎜> </u><p>In this way, when you click anywhere on the page, the click event will bubble up to the document. The event handler will determine whether the event source is the div or its sub-element with id==test. If it is a method return, otherwise it will be hidden. div can also achieve our needs. </p> <p><strong>Points to note and advantages and disadvantages</strong></p> <p>Both of these ideas rely on event bubbling, so we must pay attention to this when handling click events of other related elements to avoid the impact of the click event handlers of other related elements containing code that prevents event bubbling. This function is enabled. </p> <p>Both methods are easy to understand. It seems that the first idea is better. It seems that its processing is simpler. There is no need to judge the event source layer by layer, and the click event is directly bound to the div. This is indeed the case in this example, but it is not the case for some complex pages. If we have a page with dozens of divs on it, we need to click elsewhere on the page to hide this type of problem </p> <p></p> <div class="codetitle"> <span><a style="CURSOR: pointer" data="87485" class="copybut" id="copybut87485" onclick="doCopy('code87485')"><u>Copy code</u></a></span> The code is as follows:</div> <div class="codebody" id="code87485"> <br><div class="dialogs"><br>                                                                                                                                                                                                                                                                                                        </div><br> ;/div><br>                       </div> "2">2</div><br> <br>The code we write using idea 1 may look like this: <br> <br><br><br><br><br>Copy code<br><br><br> The code is as follows:<br> </div><script type="text/javascript"> <p> function stopPropagation(e) {</p> if (e.stopPropagation) <p> e.stopPropagation();</p> <div class="codetitle"> else <span> e.cancelBubble = true;<a style="CURSOR: pointer" data="14188" class="copybut" id="copybut14188" onclick="doCopy('code14188')"> }<u> </u>          $(document) .bind('click',function(){</a>                                                                                                           </span> $ ('. Dialog'). Bind ('click', function (e) {</div> StopPropagation (e); <div class="codebody" id="code14188">}); <br> <br> & lt;/script & gt; <br>> <br> <p>It looks simple and the same, but if we think about it carefully, we will find the problem. We have bound similar methods to each dialog. Maintaining so many click event handlers is definitely expensive in terms of memory. , causing our page to run slowly. And if we can dynamically use ajax to create a new dialog, the problem comes again. The newly created dialog cannot implement hidden functions! Because the binding function has been executed, the click event handler will no longer be bound to the new dialog. We can only do this ourselves. In other words, idea one cannot attach handlers to DOM elements that may not yet exist in the DOM. Because it binds handlers directly to individual elements, it cannot bind handlers to elements that do not yet exist on the page. </p> <p>This is the time for idea 2 to show off its skills. Let’s take a look at how the code of idea 2 is written at this time </p> <p></p> <div class="codetitle"> <span><a style="CURSOR: pointer" data="34078" class="copybut" id="copybut34078" onclick="doCopy('code34078')"><u>Copy code</u></a></span> The code is as follows:</div> <div class="codebody" id="code34078"> <br><script type="text/javascript"> <br>                                                                                                                                                                                While (eLEM) {<br> if (elem.classname && elem.classname.indexof ('dialog') & gt; >            }<br> <br>                                                                                                                                             <br>The changes are also quite small. Let’s see if we can solve the two problems above. First, no matter how many dialogs we have, we only bind a click event handler, which has little impact on performance. Add a new one Does the code of dialog idea 2 work well? It still works. In this way, we can find that idea 2 is actually a better solution in the case of complex pages. <br> <br>Now that we understand this, we can talk about the delegate method of jQuery, the second protagonist of this article. <br> <br>delegateFirst, let’s take a look at jQuery’s official syntax and description of delegate<p> <br>.delegate( selector, eventType, handler(eventObject) )<br> <br>Description: Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.</p> </div> The delegate() method adds one or more event handlers to the specified element (a child element of the selected element) and specifies the function to run when these events occur. <p> </p>Event handlers using the delegate() method apply to the current or future elements (such as new elements created by scripts). <p> </p> <p><br></p> <p>Copy code</p> <p></p> The code is as follows:<p></p> <p>$( "table" ).delegate( "td" , "click", function() {</p> $( this ).toggleClass( "chosen" );<p> });</p> <div class="codetitle"> <span><a style="CURSOR: pointer" data="966" class="copybut" id="copybut966" onclick="doCopy('code966')"> <u> Through the above statement, we can bind click event handlers to the td of all tables. </u> </a>The delegate method is designed to attach handlers to a single element or a small group of elements and listen for events on descendant elements rather than looping through and attaching the same function to multiple elements in the DOM one by one. . Attaching handlers to one (or a small group of) ancestor elements rather than directly attaching handlers to all elements in the page can provide performance optimizations. </span> </div> <div class="codebody" id="code966">jQuery version hides dialog<br><br> <br>Through the above knowledge, we can find that jQuery’s delegate method can easily realize our need to hide divs<br> </div> <p></p> <p>Copy code</p> <p><strong> The code is as follows:</strong><script type="text/javascript"> ).css('display','none');</p> <div class="codebody" id="code302">                                         ; A slight improvement, because we no longer need to bubble to the document for processing. We only need to complete the processing on the parent element of the dialog. We do not need to bind many similar functions to the document. One thing to note is that jQuery has been considerate. Help us handle this as an event source, and it will be easier to handle. <br> <br>Delegate and bind<br>Through what we have said above, we can have a certain basis for weighing whether to use bind or delegate. If you want to bind the event handler of an element separately, using bind is still very appropriate, but if When handling event handlers for many similar elements, you may want to consider delegate to see if it will help improve performance. <br> </div> </div></a></span> </div></a></span> </div></div><div class="nphpQianMsg"><div class="clear"></div></div><div class="nphpQianSheng"><span>Statement:</span><div>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</div></div></div><div class="nphpSytBox"><span>Previous article:<a class="dBlack" title="jQuery animation effect-slideUp slideDown slide up and down sample code_jquery" href="https://m.php.cn/faq/16284.html">jQuery animation effect-slideUp slideDown slide up and down sample code_jquery</a></span><span>Next article:<a class="dBlack" title="jQuery animation effect-slideUp slideDown slide up and down sample code_jquery" href="https://m.php.cn/faq/16286.html">jQuery animation effect-slideUp slideDown slide up and down sample code_jquery</a></span></div><div class="nphpSytBox2"><div class="nphpZbktTitle"><h2>Related articles</h2><em><a href="https://m.php.cn/article.html" class="bBlack"><i>See more</i><b></b></a></em><div class="clear"></div></div><ins class="adsbygoogle" style="display:block" data-ad-format="fluid" data-ad-layout-key="-6t+ed+2i-1n-4w" data-ad-client="ca-pub-5902227090019525" data-ad-slot="8966999616"></ins><script> (adsbygoogle = window.adsbygoogle || []).push({}); </script><ul class="nphpXgwzList"><li><b></b><a href="https://m.php.cn/faq/1609.html" title="An in-depth analysis of the Bootstrap list group component" class="aBlack">An in-depth analysis of the Bootstrap list group component</a><div class="clear"></div></li><li><b></b><a href="https://m.php.cn/faq/1640.html" title="Detailed explanation of JavaScript function currying" class="aBlack">Detailed explanation of JavaScript function currying</a><div class="clear"></div></li><li><b></b><a href="https://m.php.cn/faq/1949.html" title="Complete example of JS password generation and strength detection (with demo source code download)" class="aBlack">Complete example of JS password generation and strength detection (with demo source code download)</a><div class="clear"></div></li><li><b></b><a href="https://m.php.cn/faq/2248.html" title="Angularjs integrates WeChat UI (weui)" class="aBlack">Angularjs integrates WeChat UI (weui)</a><div class="clear"></div></li><li><b></b><a href="https://m.php.cn/faq/2351.html" title="How to quickly switch between Traditional Chinese and Simplified Chinese with JavaScript and the trick for websites to support switching between Simplified and Traditional Chinese_javascript skills" class="aBlack">How to quickly switch between Traditional Chinese and Simplified Chinese with JavaScript and the trick for websites to support switching between Simplified and Traditional Chinese_javascript skills</a><div class="clear"></div></li></ul></div></div><ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-5902227090019525" data-ad-slot="5027754603"></ins><script> (adsbygoogle = window.adsbygoogle || []).push({}); </script><footer><div class="footer"><div class="footertop"><img src="/static/imghwm/logo.png" alt=""><p>Public welfare online PHP training,Help PHP learners grow quickly!</p></div><div class="footermid"><a href="https://m.php.cn/about/us.html">About us</a><a href="https://m.php.cn/about/disclaimer.html">Disclaimer</a><a href="https://m.php.cn/update/article_0_1.html">Sitemap</a></div><div class="footerbottom"><p> © php.cn All rights reserved </p></div></div></footer><script>isLogin = 0;</script><script type="text/javascript" src="/static/layui/layui.js"></script><script type="text/javascript" src="/static/js/global.js?4.9.47"></script></div><script src="https://vdse.bdstatic.com//search-video.v1.min.js"></script><link rel='stylesheet' id='_main-css' href='/static/css/viewer.min.css' type='text/css' media='all'/><script type='text/javascript' src='/static/js/viewer.min.js?1'></script><script type='text/javascript' src='/static/js/jquery-viewer.min.js'></script><script>jQuery.fn.wait = function (func, times, interval) { var _times = times || -1, //100次 _interval = interval || 20, //20毫秒每次 _self = this, _selector = this.selector, //选择器 _iIntervalID; //定时器id if( this.length ){ //如果已经获取到了,就直接执行函数 func && func.call(this); } else { _iIntervalID = setInterval(function() { if(!_times) { //是0就退出 clearInterval(_iIntervalID); } _times <= 0 || _times--; //如果是正数就 -- _self = $(_selector); //再次选择 if( _self.length ) { //判断是否取到 func && func.call(_self); clearInterval(_iIntervalID); } }, _interval); } return this; } $("table.syntaxhighlighter").wait(function() { $('table.syntaxhighlighter').append("<p class='cnblogs_code_footer'><span class='cnblogs_code_footer_icon'></span></p>"); }); $(document).on("click", ".cnblogs_code_footer",function(){ $(this).parents('table.syntaxhighlighter').css('display','inline-table');$(this).hide(); }); $('.nphpQianCont').viewer({navbar:true,title:false,toolbar:false,movable:false,viewed:function(){$('img').click(function(){$('.viewer-close').trigger('click');});}}); </script></body><!-- Matomo --><script> var _paq = window._paq = window._paq || []; /* tracker methods like "setCustomDimension" should be called before "trackPageView" */ _paq.push(['trackPageView']); _paq.push(['enableLinkTracking']); (function() { var u="https://tongji.php.cn/"; _paq.push(['setTrackerUrl', u+'matomo.php']); _paq.push(['setSiteId', '9']); var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; g.async=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s); })(); </script><!-- End Matomo Code --></html>