Reputation: 11340
I have a $each loop in jquery that adds rows into a table like this:
$.each(result, function (index) {
var data = result[index];
cameraIcon = GetCameraIcon();
cameraIcon = cameraIcon.replace("$cameraId", data.CameraFQID);
var tr = "<tr><td>" + cameraIcon + "</td><td>" + icon + '</td><td>' + timestamp.format('DD/MM/YYYY HH:mm:ss') + '</td><td>' + data.DeviceLink + '</td><td>' + data.EventMessage + '</td><td>' + data.CardId + '</td></tr>';
$('#eventTable tr:first').after(tr);
});
function GetCameraIcon() {
return "<a href='javascript:;' class='cameraButton' id='$cameraId'><i class=\'fa fa-camera\'></i></a>";
}
My question is: why doesn't my jquery method fire?
$(".cameraButton").click(function () {
alert('clicked')
});
However, when I do this:
<a href='javascript:;' onclick=\"alert('clicked')\">
It works.
My guess is some careless mistake somewhere but I can't pinpoint or figure it out
Upvotes: 0
Views: 65
Reputation: 435
try this
document.getElementById("cameraId").addEventListener("click", function(){
alert("Hello World!");
});
Upvotes: 0
Reputation: 68400
If you add elements dynamically then you need to use delegated events trough on
method. This should do the trick
$(document).on('click', '.cameraButton', function() {
...
}
Direct events won't work since elements need to already exist on your page by the time you execute the statement $(".cameraButton").click(function () {}
.
Take into account that $(".cameraButton")
returns an empty array in case there no element yet with class .cameraButton
so click is bound to nothing.
Upvotes: 1
Reputation: 40030
It's probably event delegation. The new rows added to the table were not present when jQuery bound to its events, so you must use .on()
to trap the events.
Try:
$(document).on("click", ".cameraButton", function () {
alert('clicked');
});
Remember to add semi-colon to end of statements.
Upvotes: 2