i want to know how jquery' delegate or on(for

2019-01-25 20:26发布

sometimes i use on to delegate event ,

dom.addEventListener("click",function(e){
  e.target for hander.
}
instead:
dom.on("click",'a',function(){
  $(this).handler..
}

so,i guess i can write codes in this way :

function delegate(dom,event,selector,handler){
   target = event.target;
   while selector.dom.not_match event.target
       target = target.parentNode
       recheck until match the selector and do handler;
   end
}

i had wrote this before:

function delegate(dom,event,selector,handler){
    dom.addEvent event function(){
      target_arr = dom.find(selector);
      if(event.target in_array target_arr){
        do handler
      }else{
         target = target.parentNode until dom.
         recheck in target_arr;
      }
    }

}

someone know how jquery's work method on 'delegate' or 'on' for delegate?please show me the code simply description for 'delegate'..thanks alot.

5条回答
Evening l夕情丶
2楼-- · 2019-01-25 20:42
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("div").delegate("p","click",function(){
    $("p").css("background-color","pink");
  });
});
</script>
</head>
<body>

<div style="background-color:yellow">
<p>This is a paragraph inside a div element.</p>
</div>
<p>This is a paragraph.</p>

</body>
</html>
查看更多
smile是对你的礼貌
3楼-- · 2019-01-25 20:43

When you do:

$(selector1).on(event, selector2, function);

jQuery binds a handler to the event on the DOM elements that match selector1. When this handler runs, it walks the DOM hierarchy from the most specific element up to the element matching selector1, and checks whether any of the elements matches selector2. If it finds a match, it calls function with the appropriate execution context.

This is how on() is able to handle events on DOM elements that are added dynamically after the delegation is created.

查看更多
叛逆
4楼-- · 2019-01-25 20:46

Have a look at the jQuery docs for on(), they explain the concept very well.

Also, you can have a look at the source code!

The lessons learned:

  • delegate is just a wrapper for on with different parameter order
  • on does just some parameter normalisation and handles one, but delegates then to jQuery.event.add( this, types, fn, data, selector );
  • event.add does do a lot of validation, handles multiple types and special cases, pushes the arguments on $.data("events") and calls elem.addEventListener(type, jQuery.event.dispatch, false)
  • event.dispatch then queries the handles from $.data("events") again and builds a jqEvent from the native event. Then it begins searching for delegated events - the code for that is quite straightforward - and pushes them on the handlerQueue, after that the normal handlers which are attached directly on the element. In the end, it just runs the handlerQueue, starting with the delegated handlers.
查看更多
迷人小祖宗
5楼-- · 2019-01-25 20:58

With jQuery 1.4.2 launch, a new method called delegate() was introduced. This method attaches a handler to one or more events for selected/specified elements. Let's take an example. I have created a table and using delegate method, I will attach the click event handler to every td element.

<table border="1" width="200px" cellspacing="5" cellpadding="5">
   <tr>
       <td>Item 1</td>
       <td>Item 2</td>
   </tr>
   <tr>
       <td>Item 3</td>
       <td>Item 4</td>
   </tr>
</table>

jQuery delegate() method code.

$(document).ready(function(){
  $("table").delegate("td","click",function(){
         alert('I am' + $(this).text());
  });
});

It takes 3 arguments.

  1. Selector
  2. Event Type
  3. Event Handler

You will say that this is very much possible with the bind() method. Below code will serve the purpose.

$(document).ready(function(){         
  $("table td").bind("click",function(){
      alert('I am' + $(this).text());
  });
});

Then what's new with delegate() method?

bind() method will add event to element which are on the page when it was called. For example, there are only 4 td on the page when bind() was called. Later on, when you dynamically add more td in the table then bind() will not attach click event handler to those td. Let's extend our demo and place a button on the page which will add the td dynamically.

<input type="button" value="Add TD" id="btnAdd" />

$("#btnAdd").click(function(){
   $("table").append("<tr><td>Item 5</td><td>Item 6</td></tr>");
});

Now, when you run this page, you will not find click event for newly added td.

But with delegate(), you will find click event for newly added td. delegate() method adds event which are on the page and also listens for new element and add event to them. :)

查看更多
时光不老,我们不散
6楼-- · 2019-01-25 21:02

Click a paragraph to add another. Note that .delegate() attaches a click event handler to all paragraphs - even new ones.

            <!DOCTYPE html>
            <html>
            <head>
              <style>
              p { background:yellow; font-weight:bold; cursor:pointer; 
                  padding:5px; }
              p.over { background: #ccc; }
              span { color:red; }
              </style>
              <script src="http://code.jquery.com/jquery-latest.js"></script>
            </head>
            <body>
              <p>Click me!</p>

              <span></span>
            <script>
                $("body").delegate("p", "click", function(){
                  $(this).after("<p>Another paragraph!</p>");
                });
            </script>

            </body>
            </html>

another example

              <!DOCTYPE html>
            <html>
            <head>
              <style>
              p { color:red; }
              span { color:blue; }
              </style>
              <script src="http://code.jquery.com/jquery-latest.js"></script>
            </head>
            <body>
              <p>Has an attached custom event.</p>
              <button>Trigger custom event</button>
              <span style="display:none;"></span>
            <script>

                $("body").delegate("p", "myCustomEvent", function(e, myName, myValue){
                  $(this).text("Hi there!");
                  $("span").stop().css("opacity", 1)
                           .text("myName = " + myName)
                           .fadeIn(30).fadeOut(1000);
                });
                $("button").click(function () {
                  $("p").trigger("myCustomEvent");
                });

            </script>

            </body>
            </html>

working of methods for version added: 1.4.2

.delegate( selector, eventType, handler(eventObject) )

selector- A selector to filter the elements that trigger the event.

eventType- A string containing one or more space-separated JavaScript event types, such as "click" or "keydown," or custom event names.

handler(eventObject)- A function to execute at the time the event is triggered.

for version added: 1.4.2

delegate( selector, eventType, eventData, handler(eventObject) )

selector- A selector to filter the elements that trigger the event.

eventType- A string containing one or more space-separated JavaScript event types, such as "click" or "keydown," or custom event names. eventData A map of data that will be passed to the event handler.

handler(eventObject)- A function to execute at the time the event is triggered.

for version added: 1.4.3

delegate( selector, events )

selector- A selector to filter the elements that trigger the event.

events- A map of one or more event types and functions to execute for them.

查看更多
登录 后发表回答