简体   繁体   中英

JQuery use .replaceWith() on html element that was created using previous .replaceWith()

I'm working on a simple webpage that has a ton of blank div tags

<div></div>

in my css, I have the div set up as a 100px by 100px square with a background color.

I'm using jQuery to have the mouse interact with the divs by changing color, and when clicked, the div breaks down into four smaller squares, within the space of the original square. The smaller squares are created with a .replaceWith() call. This all works great.

My problem is that if I click one of the smaller squares, I want it to .replaceWith() four more smaller squares in it's position, but It doesn't do anything.

Here is my jQuery

$(document).ready(function(){

$(document).on('mouseover', 'div', function(){
    $(this).css("background-color", "#4499FF");

    $(this).mouseleave(function(){
        $(this).css("background-color", "#2277AA");
    });

});

$(document).on('click', 'div', function(){
    $(this).replaceWith('<div><div class="small"></div><div class="small"></div><div class="small"></div><div class="small"></div></div>');
});
$(document).on('click', '.small', function(){
    $(this).replaceWith('<div><div class="small"></div><div class="small"></div><div class="small"></div><div class="small"></div></div>');
});

});

and my css has a .small{} with the width and height set to 50% so by definition, I believe it should work.

I don't think you need .replaceWith for this. You could simply use .append . Also, since .small is a <div> , it will trigger both document click handlers, which does not seem like the intended behavior. Also, by binding the mouseleave event inside the mouseover event, you are binding it multiple times for every div.

I would suggest enabling mouseover events only on the innermost <div> elements and using append instead:

// Split into 2 events
// Use :not(:has(div)) to ensure that the div has no children
$(document).on('mouseover', 'div:not(:has(div))', function () {
    $(this).css("background-color", "#4499FF");
});
$(document).on('mouseleave', 'div:not(:has(div))', function () {
    $(this).css("background-color", "#2277AA");
});

$(document).on('click', 'div', function (e) {
    // Only append the elements to the target element clicked
    // This prevents unwanted behavior when clicking a div inside a div.
    if (e.target == this) {
        $(this).append('<div class="small"></div><div class="small"></div><div class="small"></div><div class="small"></div>');
    }
});

Example Fiddle

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