briansol briansol - 1 year ago 60
Ajax Question

jQuery ajax return elements can't be selected

I'm having an issue with ajax generated selectors.

basically i have a start button in default state.
onclick, it starts something, and then the click also brings in a new div from an ajax call with results. one of these items is the stop button.
my linked script from the main page has a click event attached to this stop button

<a id="stop">stop</a>

If I put the script inline, in the return call it self that also prints the anchor, i can access it with

$('#stop').click(function() { });

However, I don't want the script there (as there are multiple items per page and it makes much more sense to have it in the main linked resource). If this call is in the linked sheet from the main page, nothing happens.

Why is this?

Is there another 'document ready' wrapper i should use to address return elements?

Answer Source


<div id="container"></div>

is the element which you're appending the results of the ajax call to,

You want to do:

$('#container').on('click', '#stop', function() { console.log('test'); });

Alternatively you could do something like

$('#stop').live('click', function(){ console.log('test'); });

But I wouldn't recommend that if you are going to have a lot of events on the page to handle, because live adds overhead every time it's used.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download