开发者

Problems with .prepend method in jQuery

开发者 https://www.devze.com 2022-12-21 02:07 出处:网络
I have a function that prepends a 开发者_如何转开发li tag to a parent div just fine...however, after the prepend, i want to act upon this prepended list item by changing css properties when hovered on

I have a function that prepends a 开发者_如何转开发li tag to a parent div just fine...however, after the prepend, i want to act upon this prepended list item by changing css properties when hovered on but the jQuery selector can't find it (seemingly because the .hover function is searching for list items available to act upon when the page loads..and the prepended items are nonexistent when the page loads).

My prepend code looks like this:

$("div#content-text div#sub-text").prepend(
"<li id='item1' class='contents-rec'><div class='text'></div></li>");

while my hover code (not working) looks like this:

$("div#content-text div#sub-text li.contents-rec").hover(function(){
$(this).css({border:'1px solid #fff'});
}, function(){
$(this).css({border:''});
},0);

any help would be greatly appreciated!! thanks in advance


If you are dynamically inserting an element after the hover event has already been assigned on the page load, you can use live() in that situation (jQuery 1.4.1 or greater required for 'hover' parameter):

$("div#content-text div#sub-text li.contents-rec").live('hover',
    function(event) { 
        if (event.type == 'mouseover') {
            $(this).css({border:'10px solid orange'}); 
        } else {
            $(this).css({border:''}); 
        }
});


Are you executing this line...

$("div#content-text div#sub-text li.contents-rec").hover(function(){ $(this).css({border:'1px solid #fff'}); }, function(){ $(this).css({border:''}); },0);

After this one...

$("div#content-text div#sub-text").prepend( "");

If so it should be there.

Also check out the live() method. here


The code you're showing doesn't actually prepend anything, so I'm assuming that you just left it out for ease of posting. (We can help you much better if you post actual working code, though.)

Then, make sure that your hover code is running after the prepend code. If that isn't happening, you'll need to adjust things somehow. (Maybe with setTimeout(...).)

JQuery's live() could help, but version 1.3.x doesn't support "hover" in the live() binding.

0

精彩评论

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