开发者

Is there a JQuery event that detects mere presence?

I'm using an ajax call to render a partial. The problem is that when the call finishes, my jquery code applies to the newly inserted HTML only if I use the live() method (as far as I understand).

I've开发者_如何学Python successfully used the live() method for those selectors that have 'click' events attached to them. Example:

$('.course_name_click').live('click', function(e) {
    $(this).closest('div').next().slideToggle('slow');
    e.preventDefault();
 });

But I'm not sure how to use live() for a simple hide() function. That is, I'd like an HTML snippet to be hidden when it first appears. I thought load() might work, but it doesn't. Any suggestions?

$('.descrip_body').live('load', function(e) {
    $('.descrip_body').hide();
});

Just to be clear, I want to transform

$('descrip_body').hide();

to a version that uses live().


In response to an answer, tried to attach a hide() callback to the AJAX request. But it still didn't work (i.e. the relevant HTMl wasn't hidden). Here's that code:

$("#courses_body").html("<%= escape_javascript(render :partial => 'courses') %>", function() {
    $('.descrip_body').hide();
});


Two questions:

1- Can't you load your html with a class that has a display:none style already?

2- Could you not put your $('.descrip_body').hide(); code on your success callback function?

I know this is not exactly what you asked, but they might work as well...


It looks like you don't actually have an AJAX request — an AJAX request would hit a specific URL, return the markup from the URL, and fire a "success" method as the callback. jQuery uses $.ajax, $.post, and $.get to do this.

$.html is much more straightforward — it injects a string of markup into the DOM immediately. That's what you're using, because the Rails partial is putting that string directly into your $.html() argument.

So, from what I gather, you shouldn't actually need a callback, or any kind of event, because what you're doing is not asynchronous...you don't have to wait for your markup to appear on the page; you can just inject it and start operating on it. Try:

$("#courses_body")
  .html("<%= escape_javascript(render :partial => 'courses') %>")
  .find(".descrip_body")
  .hide();


How is the HTML snippet being loaded in the first place? Why don't you just hide it when the AJAX call returns?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜