I am trying to write a generic table generator where I can tell it the function to call in the onclick event of each cell. The function is then defined somewhere else on the page.
The problem is I cannot get the page to evaluate the function at the right moment. I want it to convert my string to a function when it is building the DOM not when it fires the click event. Maybe this is not possible in Javascript/JQuery?
A simplified version of the code I originally wrote server-side in C# is:
string functionCall = "DoSomething(4);";
TableCell detailCell = new TableCell();
detailCell.Attributes.Add("onClick", functionCall);
functionCall = "DoSomething(5);";
detailCell = new TableCell();
detailCell.Attributes.Add("onClick", functionCall);
This then worked when it was rendered as html in the browser. It turned into:
function DoSomething(p)
{
alert(p);
}
<td onclick="DoSomething(4)"></td>
<td onclick="DoSomething(5)"></td>
I want to replicate this functionality in Javascript.
If I do:
var functionCall = 'DoSomething(4);';
$('#detailCell').attr('onclick', functionCall);
it won’t fire the event in IE7 for some reason but fires it in Chrome.
If I do:
var functionCall = 'DoSomething(4);';
$('#detailCell1').click(function () { eval(functionCall); });
functionCall = 'DoSomething(5);';
$('#detailCell2').click(function () { eval(functionCall); });
then it doesn’t change functionCall to a piece of text when the click event is added. Instead it evals functionCall WHEN the cell is clicked. This means the value of functionCall is now wrong.
e.g. it always does DoSomething(5) even if I click on detailCell1 because that was the last value of functionCall.
If I do:
var functionCall = 'DoSomething(4);';
$('#detailCell1').click(eval(functionCall));
it runs the function in functionCall immediately when adding the click event rather than when it is clicked.
I hope this makes some sense as it is difficult to explain.
Basically I just want to be able to do
<td onclick="any javascript I feel like storing in a string"></td>
using JQuery.
Is this even possible?
This is my first ever post on stackoverflow so please be gentle…
Try this…
What happens here is that you capture the string at the time that you create the handler by assigning it to the parameter ‘code’.
In your current scenario the click handler uses the value of the string at the time it is clicked and not at the time the handler is created.
This is called a closure!
The functionCall value is assigned to the code parameter.
Now when you change functionCall the code parameter still refers to the old value.