Attach jQuery Click Event to Binding Icon

I have a light SO. Why can't I bind the click event directly to the bind id? I should have indicated that I also use jQuery Mobile.

<div id="foobarNavbar" data-role="navbar" style="display:none;"> <ul> <li><a id="foo" href="#foo" data-icon="plus">New Event</a></li> <li><a id="bar" href="#bar" data-icon="grid">Events</a></li> </ul> </div><!-- /foobarNavbar--> 

I am trying to attach a click event to foo. This does not work:

  $('#foo').bind('click', function(e) { e.preventDefault(); console.log("You clicked foo! good work"); }); 

This works, but gives me a click event for foo and bar. Is it not possible to bind the bind identifier or am I making a rookie mistake?

  $('#foobarNavbar ul li a').bind('click', function(e) { e.preventDefault(); console.log("You clicked foo! good work"); console.log(e); }); 
+4
source share
3 answers

Important: use $ (document) .bind ('pageinit'), not $ (document) .ready ()

The first thing you learned in jQuery is to call the code inside $ (document) .ready (), so everything will be executed as soon as the DOM loads. However, in jQuery Mobile Ajax is used to load the contents of each page into the DOM when navigating and the DOM readiness handler is executed only for the first page. To execute the code whenever a new page is loaded and created, you can bind to the pageinit event. This event is described in detail at the bottom of this page.

I tried to link using a document ready instead of pageinit. First function

 $('#foo').bind('click', function(e) { e.preventDefault(); console.log("You clicked foo! good work"); }); 

works great when moving to the 'pageinit' event. However, I'm still not sure why the second code example worked, but not the first.

+1
source

Wrap this code in a ready document, and it should work if you don't have other script errors and you loaded jQuery.

 $(function(){ $('#foo').click(function(e) { e.preventDefault(); console.log("You clicked foo! good work"); }); }); 
+2
source

As if it would work, I think ...

 $('#foobarNavbar').on('click','#foo', function(e) { e.preventDefault(); e.stopPropagation(); console.log("You clicked foo! good work"); console.log(e); }); 
+1
source

All Articles