0

I have a function, which appends a div into a div(2). Inside div(2) I have a span. if I click this span, a function shall be executed.(click() function)

Currently I can not apply any function by onclick(), if div(2) gets inserted by jQuery. If I insert div(2) directly (hardcoded) I can execute the function.

How can I apply a function to an object which is inserted by jQuery?

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
ina
  • 3
  • 1

2 Answers2

1

Use delegate() to handle events for future elements — those which are not yet part of the DOM:

$(document).delegate(".div2 > span", "click", function () {
   // handle click event here
});
Andy E
  • 338,112
  • 86
  • 474
  • 445
0

Ideally you want to have your jQuery code that inserts the element also attach the click handler.

So extend your function that calls

$(div).append(div2)

To also call

$(div2).find("span").click(function() {

});
Raynos
  • 166,823
  • 56
  • 351
  • 396