Reputation:
I am trying to use delegate to call a function, when a specific set of links get click. I have already used it before in some other page. It was worked there. But, this time i even not able to find, where the problem is.
My links were dynamically generated, they looks like
<a class="thumbLink" href="#" id="My HomeTown-1"><small>My HomeTown</small></a>
And the jQuery delegate function is,
$(document).ready(function(){
$("#albumHolder").delegate('a.thumbLink', 'click', this.loadAlbum);//albumHolder is div ID that holds all the <a> elements
this.loadAlbum = function(){
var id = this.id;
var number = id.lastIndexOf("-");
var alubmName = id.subString(0, number);
alert(albumName);
}
});
Update:
I tried both versions, But i am not able to make it work!
$("#albumHolder").delegate('a.thumbLink', 'click', function loadAlbum(){
var id = this.id;
var number = id.lastIndexOf("-");
var alubmName = id.subString(0, number);
alert(albumName);
});
this.loadAlbum(){
var id = this.id;
var number = id.lastIndexOf("-");
var alubmName = id.subString(0, number);
alert(albumName);
}
$("#albumHolder").delegate('a.thumbLink', 'click', this.loadAlbum);
The above code is in $(document).ready(function(){});
. Is that correct??
i also tried by putting them in a separate js
file. I cannot make it work.
Any idea about my problem!!!
Upvotes: 3
Views: 2889
Reputation: 318498
You use a function expression before defining it. This doesn't work. Either use a regular function declaration (function loadAlbum() { /* ... */ }
) or define this.loadAlbum
(this.loadAlbum = function() { /* ... */ }
) before using it in your delegate() call.
Upvotes: 4
Reputation: 322492
If that's the order of your actual code, you're trying to pass the function expression before it has been initialized.
Reverse them and it should work:
this.loadAlbum = function(){
var id = this.id;
var number = id.lastIndexOf("-");
var alubmName = id.subString(0, number);
alert(albumName);
}
$("#albumHolder").delegate('a.thumbLink', 'click', this.loadAlbum);
Upvotes: 5