开发者

jQuery: if hovering over an element injects something into the DOM, can I still reference it?

If hovering over an element injects something into the DOM, can I still开发者_运维技巧 reference it?

Or do I have to use the live plugin?

I'm using jQuery 1.3.2

i.e. can I do

$("#someItem").attr("src", "htt...")

on it?

I am trying to do it, but I think its not working b/c its a newly added item to the DOM.


Yes, an element that has been added to the DOM can be selected and referenced.

Or, if you already had a reference to it that you used when you added it to the DOM, you can continue to use that reference after it has been added as well.

Using this example, you can see that you can both use a current reference to a newly created element, as well as make a new reference to it.

http://jsfiddle.net/Czuvx/

HTML:

<div id='button'>hover me</div>

jQuery:

$('#button').hover(function() {
    $('#newElement').remove();

    var $myNewElement = $('<div id="newElement">new Element</div>');

    $('body').append($myNewElement);

    $myNewElement.css({color:'red'});
},
function() {

// This function has completely different namespace 
//   from the one that created and inserted #newElement
//   and I can get a reference to it just like any other element

    var $newReferenceToElement = $('#newElement');

    $newReferenceToElement.css({color:'blue'});
});


Showing a bit more of your code would be helpful, but I think I get the general idea.

If you're just looking to add events or something to that item, you can do it before you append the item.

(function($){
  $(function(){
    $("#link").hover(
      function(){
        var $div = $("<div class='inserted_div'></div>").bind("click",function(){ ... });
        $("body").append($div);
      }),
      function(){

      });
  });
})(jQuery);

So just bind the events or attributes at the time of creation, before you append it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜