Is there a onAvailable() function in jQuery?

泄露秘密 提交于 2019-12-02 11:32:50

If #chat is in the chatBox.html that you are loading then you can take advantage of the callback that load has:

$('#loader').clone().removeAttr('id').load("Views/chatBox.html",function(){
    $('#chat').focus(function() {
        $(this).addClass('jV');
    })
    .blur(function() {
        $('#chat').removeClass('jV');
    });
}).appendTo('body');

http://docs.jquery.com/Ajax/load#urldatacallback

Use jQuery.live() instead. live() will bind event handlers when the elements are created. It requires jQuery 1.3+.

Edit: It looks like the chat div is probably isn't loaded yet, so that's still a problem. I would suggest you change your scheme somewhat. First, in your document have an area where all the chats are:

<div id="chat"></div>

and then you have:

$(function() {
  $("#chat div.chat").live("focus", function() {
    $(this).addClass("jV");
  }).live("blur", function() {
    $(this).removeClass("jV");
  });
});

The difference here is that you're adding divs with a class of chat to the chat area (which has an id of chat). Then you simply do:

$('#loader').clone().removeAttr('id').load("Views/chatBox.html").appendTo('#chat');

If you are adding listeners to elements that are part of the new HTML/DOM elements created on the fly you can just attach the events to those elements created as you create them using any of the jQuery event handlers that are appropriate.

If there are issues with content that's being loaded externally (like scripts/images) use the .load() jQuery event handler on those elements to detect when they are available in the DOM and can be manipulated.

As mentioned by another poster, .live() works too but might not be required if you have control over the element creation yourself - .live() adds some overhead that might be overkill.

Livequery will do what you want. It will

"bind events or firing callbacks for matched elements auto-magically, even after the page has been loaded and the DOM updated."

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!