简体   繁体   中英

Create a div with jquery on hover?

So I've got a pretty stupid question. Is it possible, to create a div on hover? I don't have access to the file that creates a list for me, so it creates this.

<ul class="class">
    <li>content</li>
    <li>content</li>
    <li>content</li>
</ul>

In this particular project, I can't edit that file directly. but I'd like to create a on the outside of each list item

   <div>stuff</div><li>content</li>

I know it's not an IDEAL setup, but it's the way I'd like to do it. Worse comes to worse, I've got another way that WORKS, but I'd like -

something like

jQuery('#target').hover(function() {
    jQuery(this).find('<li>').echoBefore('<div class="class">stuff</div>')
    });

That would be my IDEAL solution to the sticky situation I've got :P

You will want to use the method append

like so

jQuery('#target').hover(function() {
    jQuery(this).find('li').append('<div class="class">stuff</div>')
});

if you want to access this div after appending it, you can use jquery's method of creating a new element like this

jQuery('#target').hover(function() {
    var div = jQuery('<div></div>');
    div.addClass('class').html('stuff');
    jQuery(this).find('li').append(div);
    div.html('this is updated html after appendage');
});

To create the DIVs on the outside of each LI you can use the following code:

jQuery(this).find('li').before('<div class="class">stuff</div>');

However, if it's all the same, I would recommend creating those DIVs on the inside of the LIs using this code:

jQuery(this).find('li').prepend('<div class="class">stuff</div>');

This would work:

$('#target').hover(function(){
    $(this).find('li').append('<div>stuff</div>');
});

But,when you hover multiple times, the div would be created multiple times.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM