Hi, I have a table that is generated by php (it has to be). Each row has a link that calls a javascript function. When the table is generated each link is given a number to put in the function call, like so:
Then in my javascript I can do something based on the number:
function doSomething(number) {
// do something with number. ajax call etc
}
But in jquery, I noticed that you define the onclicks in the code itself and not the links:
$("#linkid").click(function(){
// do something. But how can I distinguish between each link?
});
I could have one function for each link, but that seems silly and long winded. Plus I don’t know in advance how many rows will be generated. It could be 5000 rows!
What is the way around this? I’m a bit confused by the move over to jquery tbh.
You could bind a function to the click event like so:
$(document).ready(function() {
$("#myTable a").click(function(e) {
e.preventDefault(); // Stop the normal behavior that would happen with a click
// Use $(this) to act upon the link that was clicked
alert("The ID of the clicked link is " + $(this).attr("id"));
// Change the background color of the clicked row
$(this).closest("tr").css("background-color", "red");
});
});
Hopefully that gets you pointed in the right direction.
It seems that I having trouble making this work on a table that has been inserted into the DOM. Take this example:
table_test.html:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// Ajax setup
$.ajaxSetup ({
cache: false
});
var ajax_load = "Loading...";
// On locality change
var loadUrl = "tab.html";
$("#load").click(function(){
$("#tab")
.html(ajax_load)
.load(loadUrl);
});
$("#myTable a").click(function(e) {
e.preventDefault(); // Stop the normal behavior that would happen with a click
// Use $(this) to act upon the link that was clicked
alert("The ID of the clicked link is " + $(this).attr("id"));
// Change the background color of the clicked row
$(this).closest("tr").css("background-color", "red");
});
});
</script>
</head>
<body>
<a href="#" id="load">Load table</a>
<div id="tab">
</div>
</body>
</html>
Yeah, when using elements inserted into the DOM you can’t just use the .click() event. In the past you might use .live(“click”, function() {}), but with jQuery 1.7, .on() is the way to go.