0

I'm appending HTML elements with clickevents via jQuery. The creation must be able to give these clickevents variables, I end up in

NOT DEFINED ERRORS.

function foo( bar ){
  // do something with bar
}; 

var bar = "lolbert";

$("#parent").append("<td onclick='foo(" + bar + ")'> Whatever </td>");

Of course, the last line ends in the element:

<td onclick='foo( lolbert )'> Whatever </td>

And the clickevent will cause a "lolbert is not defined" error. It's clear why this happens and that it doesn't work this way. However, whats the correct way to handover variables for events created by jQuerys .append() ?

2
  • 1
    You forgot ' after onclick='foo(' + bar + ')'>! Commented Jul 27, 2015 at 8:40
  • 1
    " missed: $("#parent").append("<td onclick='foo('" + bar + "')> Whatever </td>"); Commented Jul 27, 2015 at 8:48

1 Answer 1

2

You can add the onclick handler functionally:

var bar = "foo";
$("#parent").append($('<td>Whatever</td>').click(
  function() {
    alert(bar);
  }));
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.