views:

66

answers:

3

So I have a container div, within it, using .load I load some content from db, after the .load the result will be something like

<div id="results">
  <div id="a1" class="search-result"></div>
  <div id="a2" class="search-result"></div>
</div>

As I understand it, I should be able to select the nested div's by using $("#results .search-result") but I just cant get it to work. If I try:

$("#results .search-result").click(function() {
 alert('click');
}

it just doesnt seem to work. It does work if I use:

$("#results").click(function() {
 alert('click');
}

the only thing I can think of is that because the nested div's are loaded using .load then it might not be able to see them?

any help?

A: 

The event handlers are attached to the DOM elements in your example, and are getting erased when the div is loaded because the elements are replaced. Try this instead:

$("#results .search-result").live('click', function() {
 alert('click');
});

.live() is a handler that sits up at the document level instead capturing the clicks as the bubble up...and get erased with the .load()

Nick Craver
+1  A: 

If those search results is added after the fact you need to use live() instead.

$("#results .search-result").live("click", function() {
  alert('click');
});

Plus your code had a syntax error (note the final line). It's good practice to look at your errors console to see these kinds of JS errors.

Lastly I'm assuming your snippet is a simplification because what you have is (depending on your CSS) zero height so you might not be able to click on it.

cletus
+1 great answer, quick to spot all those :)
Sarfraz
A: 

$().click() just adds the click handler it matching element that exist at the time the click() function is called. If you want the event handler added to elements that are added later, use the live() function

James Curran