开发者

Jquery load content and use it

I try to load some external data into a div.

var $j = jQuery.noConflict();
$j(document).ready(function(){
 $j('#fotos').load('/diary');
});

This works perfectly but when i try to add

$j('.previous_month a').click(function () 
 { 
  $j('#fotos').load('/dairy/10');
 });

The new data contains a class previous_month with links inside it. But when i click on a link inside the previous_month div, there is nothing happening, even if i substitue .load with alert('aazz');

Do i mis 开发者_开发百科something?


The .click() handler attaches itself when it's first run. That is to say, when your code executes for the first time, any .previous_month a found has the click handler attached.

As you are dynamically adding this DOM content, the click handler hasn't been attached (because it didn't exists when first run).

What you are looking for is the .live() handler. It performs essentially the same way, but it doesn't care when you add the content.

so your handler becomes:

$j('.previous_month a').live('click', function () 
{ 
    $j('#fotos').load('/dairy/10');
});


use live like this

$j('.previous_month a').live("click", function () 
 { 
  $j('#fotos').load('/dairy/10');
 });


yes, you need to use jquery.live to do the binding. The .click only binds to what exists in the dom when it's run, not what gets added to the dom See http://api.jquery.com/live/

Changing your

$j('.previous_month a').click(function () 
 { 
  $j('#fotos').load('/dairy/10');
 });

TO 
$j('.previous_month a').live('click', function() {
  // Live handler called.
});

instad will work


You may be able to solve that by using jquery's live function:

$j('.previous_month a').live('click', function()
 { 
  $j('#fotos').load('/dairy/10');
 });

http://api.jquery.com/live/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜