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 becau开发者_运维问答se the nested div's are loaded using .load then it might not be able to see them?
any help?
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.
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()
$().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
精彩评论