开发者

How to create custom event in jQuery

Hi I'd like to describe a scenario I'd like to accomplish, and I have no idea how to

I'd like to bind\live on an element to a custom 'myclick':

$('#somediv').bind('myclick', function() {});

obviously, I'd like to trigger this event only when something happens to that element, e.g. if myclick has occurred on that element

I know how to trigger a custom event on a specific element (http://api.jquery.com/category/events/event-object/)

Clarifications to the question:

I will define what does myclick mean (e.g. 3 clicks in a row on that element)

how can I tell wh开发者_C百科en it happened on 'somediv' ?

Do I somehow register via jquery to elements that did bind\live on them? if so, how?

a complete example is:

<html>
<head>
   <script to include jquery>
   <script to include MYCODE.js>

   <script>
     $('#somediv').bind('myclick', function() { alert('myclick'); } );
   </script>

   <body>
      <div id='somediv'></div>
   </body>
<head>
</html>

so my question is: what does MYCODE.js contain?

how can it tell that some custom logic that it defines, happened on 'somediv' ?

Thanks for your help


.trigger() is the method you are looking for. It must be called on the same DOM element that you used in .bind()

$('#somediv').trigger('myclick')


Exactly as Jeff says, you need to call $('#somediv').trigger('myclick'); in any logic that should cause the event to fire. Your binding example in your original question looks right to me, so that should be all you need to do.


I ended up writing a plugin for this - a good place to start is at http://blogs.sitepoint.com/how-to-develop-a-jquery-plugin/ and http://starter.pixelgraphics.us/

I've written my plugin, and placed it here if anyone is interested.

http://code.google.com/p/jquery-touch-area/

Enjoy

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜