Reputation: 914
I have weird problem. At first I didn't want to use .on() method because I couldn't get it to work at all, so I used .live().
Now, I'm writing a new jQuery script and I used .on() heavily and it works. Until now.
jQuery code:
$('#artistList a').on('click',function(e){
console.log($(this).parent().text());
e.preventDefault();
});
HTML Code:
<div id="artistList">
<div class="artist"><a class="delete" href="#"></a>Psy</div>
<div class="artist"><a class="delete" href="#"></a>Fernanda Martins</div>
<div class="artist"><a class="delete" href="#"></a>DJ Nreal</div>
</div>
Also tried this methods:
$('#artistList>a').on('click',function(e){
$('.delete').on('click',function(e){
No luck. What am I missing?
This is the only part that doesn't work
I have read the documentation about .on() and based on that, this should work. Also, I'm using the latest jQuery, (jquery-1.8.3.min.js).
EDIT
<a>
elements have a width: 15px
and height: 15px
in CSS, so they are visible.
Upvotes: 4
Views: 3289
Reputation: 532575
In order to work like live
you need to delegate the handler to a higher level element.
$('body').on('click','#artistlist a', function(e) {
// note the change to the selector to reflect your actual mark up
// handler body
});
Using this form of on is required if the elements to which the handler should apply are added dynamically after the page is initially loaded. Note also that the handlers should be applied after the DOM is loaded either by placing scripts just before the end of the body element or using the ready
event handler, $(function() { ... });
If a handler sometimes works and sometimes doesn't it's likely a race condition on page load between the elements being loaded into the DOM and the script being invoked. This is usually a sign that you've omitted adding the handlers inside the ready event handler.
Upvotes: 8
Reputation: 106443
Your links (<a>
elements) are empty here, so they obviously fail to catch click
event. I suppose you forgot to move those Psy
, Fernanda Martins
etc. inside <a href="..."></a>
.
Also, only the second selector will actually collect these links (as all they have class delete
on them). The first one - '#artistList>a'
- tries to find the anchors that are direct descendants of the element with artistList
id. But it's destined to fail in this noble quest, because there's another layer separating them - <div class="artist">
. So the rule should probably be something like '#artistList a'
.
Upvotes: 4