Reputation: 49
I am having some trouble trying to store the url parameters of some dynamic links that I created with an ajax post response. The ajax post is working correctly and the name and subgenre vars are being properly filled from the ajax response. Now what I would like to happen is that a user clicks on one of the generated urls, the parameters inside of the urls, i.e. subgenre="blah", are going to be sent to a database and stored. The problem I am having is that a standard event click function will not work inside or outside of the document ready function.
$(document).ready(function() {
$.each(data, function() {
$('#artist-suggestions').append('<li><a href="http://...../100.php" artist="'+ this.name +'" subgenre="'+ this.subgenre +'" onclick="artistGen()">' + this.name + this.new + '</a></li>');
});
});
I then created an onclick function, as below, but I can not use the "this" query because it is outside of the document scope. I had to put the onclick function outside of the document ready function or else it would not work.
function artistGen(){
alert('dfdsf');
};
What am I missing here or what am I doing wrong?
Upvotes: 1
Views: 322
Reputation: 97672
That's just how it is a function called in those event attributes have to be defined globally(or defined right there) not in any wrapper function. A better solution would be to attach event handlers.
$(document).ready(function() {
function artistGen(){
alert(this.href);
};
$.each(data, function() {
var $li = $('<li><a href="http://...../100.php" artist="'+ this.name +'" subgenre="'+ this.subgenre +'">' + this.name + this.new + '</a></li>');
$li.find('a').on('click', artistGen);
$('#artist-suggestions').append($li)
});
});
Upvotes: 0
Reputation: 7568
You need to remove the artistGen()
function from the scope of the .load()
$(window).load(function(){
$('#artist-suggestions').append('<li><a href="http://...../100.php" artist="jim" subgenre="subgenre" onclick="artistGen()">jim new</a></li>');
});
function artistGen(){
alert('dfdsf');
}
Upvotes: 0
Reputation: 451
In jQuery for dynamic elements you can use the click event in this way
$('#artist-suggestions li').on('click', 'a', function() {
// do something
});
or you can continue with the way you did, by using a function but just add a parameter to that function like
function artistGen(Artist){
// do something
};
Upvotes: 0
Reputation: 2238
You can pass these in the onclick function when you make each element.
$(document).ready(function() {
$.each(data, function() {
artist = this.name;
$('#artist-suggestions').append('<li><a href="http://...../100.php" artist="'+ this.name +'" subgenre="'+ this.subgenre +'" onclick="artistGen(' + this.Blah1 + ',' + this.Blah2' + ')">' + this.name + this.new + '</a></li>');
});
})
;
function artistGen(Blah1, Blah2){
saveData(Blah1, Blah2);
alert('dfdsf');
};
Upvotes: 1