Reputation: 1076
I try to call a custom made function from a link but somehow it doesn't work. Alert doesn't pop up. Help appreciated! This is my code:
$.each(data.Tables, function(i, data){
link = '<a href="#" onclick=test()>' + data.tableName + '</a>';
tr.append("<td>" + link + "</td>");
tr.append("<td>" + data.rowCount + "</td>");
$("#tablesTable").append(tr);
});
This is my function:
function test (){
alert("Doesn't work");
}
If I change the link row to this, alert comes after clicking the link.
link = '<a href="#" onclick=alert()>' + data.tableName + '</a>';
Upvotes: 1
Views: 939
Reputation: 3974
Change this
link = '<a href="#" onclick=test()>' + data.tableName + '</a>';
to this
link = '<a href="#" onclick="javascript:test();">' + data.tableName + '</a>';
Upvotes: -1
Reputation: 227310
JavaScript has no place in HTML attributes. jQuery can actually bind event handlers to elements even if they are not in the DOM, so I'd suggest you do something like this:
$.each(data.Tables, function(i, data){
var $link = $('<a></a>', { // Create a new jQuery object
href: '#',
html: data.tableName
}).click(function(){
// Your code here...
alert("Doesn't work");
});
// We can't use '+' since $link is no longer a string
tr.append($link.wrap('<td></td>').parent());
tr.append("<td>" + data.rowCount + "</td>");
$("#tablesTable").append(tr);
});
This uses jQuery to create the <a>
tag, then uses .click()
to bind the event.
Upvotes: 3