3

Why following doesn't work:

$(function()
{
    $('#settings').on('click', '.link', function(e)
    {
        e.preventDefault();
        alert('okay');
    });
});

...when just prepending body to selector makes it work?

$(function()
{
    $('body #settings').on('click', '.link', function(e)
    {
        e.preventDefault();
        alert('okay');
    });
});

This code is executed by $.getScript(...) call just after #settings is inserted into DOM by $('body').append(...).
I want to use .on() since .links can be created dynamically and I don't want to rebind events all over the place.

Browsers affected: Firefox, Chrome, possibly more
JQuery version: 1.11.0

rr-
  • 14,303
  • 6
  • 45
  • 67
  • Fixed closing brackets. jsFiddle is a problem since it'd need to make mentioned $.getScript call which I feel is mandatory to reproduce the case. – rr- Mar 08 '14 at 21:32
  • Can you post more code? Can it be you are using AJAX and the `$('body').append(...)` is happening later than you expect? – Sergio Mar 08 '14 at 21:34
  • I will provide more code ASAP; the basic idea is that `$.getScript()` call occurs inside AJAX success handler, right after appending the content from AJAX call. – rr- Mar 08 '14 at 21:38
  • What do you get if you do `console.log($('#settings'));` just before `getScript`? – Sergio Mar 08 '14 at 21:39
  • 1
    And, I must ask, you have just one `#settings`, right? ( i can remove this comment to not polute when you answer) – Sergio Mar 08 '14 at 21:41
  • You're brilliant, turns out I had two elements with the same ID. :facepalm: I was logging just `$('#settings').length` and it was 1 so I thoguht it's ok - it couldn't actually show the extra element. Please provide an answer so I can accept it. – rr- Mar 08 '14 at 21:46

1 Answers1

1

ID's must be unique.

In this case it seems you might have more than one element with the same ID, thus the odd behaviour you are getting.

Community
  • 1
  • 1
Sergio
  • 28,539
  • 11
  • 85
  • 132