简体   繁体   中英

jQuery load div into another without .html() method

I have a div (let's call it potatoes) that I want to appear inside another div (food). The typical way to do this would be:

$("#food").html ( $("#potatoes").html()); 

However this doesn't accomplish what I want. Instead of using the actual "potatoes" div, jQuery seems to be copying that content into the food div, where the original content still exist in the browser.

I want the ACTUAL div (potatoes) to disappear from its place and to appear in the container div (food) without having to do perform .hide() ... or similar methods.

Reason why? I have selectors that enable and disable buttons in the potatoes div, and they seem to trigger the original potatoes div content, but NOT the duplicate that has been loaded into the food div.

Does that make sense? Can anyone give insight as to why this is and what I should do?

Side note:

$(document).on('click','#button-loaded-with-page', {} ,function(e){
    this.disabled = true;
    $('#button-inside-potatoes-div').hide();
});

The above example is what I would like to achieve, but does NOT hide the button when the potatoes content has been loaded into food by the .html() method. Instead it hides the original button on the page, and not the duplicated one.

What I am trying to achieve: https://jsfiddle.net/o9kshscj/6/

You can just pass the object to html()

$("#a").html($("#b"));

Demo: Fiddle

You could use append to change the parent. This will move the #potatoes object out of it's current DOM position, into the #food div as a child

$("#food").append($("#potatoes"));

You can just remove the div after replacing like this:

$("#a").html($("#b").html());
$("#b").remove();
$("#button-to-enable").prop("disabled", false);

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