jQuery copying content between DIVs

天涯浪子 提交于 2020-01-06 05:08:06

问题


I am working on a website that I want to be entirely Javascript based: you load the website, then all the pages are pulled in by Javascript.

So I here's what I have:

    <span id="deathWormButton">Death Worm</span>
    <div id="pageContent">
        <p>Thanks for taking the time to view my portfolio!</p>
        <p>Placeholder content</p>
        <p>Placeholder content</p>
        <p>Placeholder content</p>
        <p>Placeholder content</p>
    </div>
    <div id="DeathWormPage" class="page">
        <p>Thanks for taking the time to view my portfolio!</p>
        <p>Placeholder content</p>
        <p>Placeholder content</p>
        <p>Placeholder content</p>
        <p>Placeholder content</p>
    </div>

And here's my jQuery:

        $(document).ready(function()
        {
            $(".page").hide();
        });
        $("#deathWormButton").click(function()
        {
            $("#pageContent").innerHTML = $("#DeathWormPage").innerHTML;
        });

But it doesn't work! (View here)

So how do I copy content from the div id="DeathWormPage" into div id="pageContent" when the deathWormButton is clicked?


回答1:


jquery objects do not have an innerHTML property.

$(document).ready(function () {
    $(".page").hide();

    $("#deathWormButton").click(function () {
        $("#pageContent").html($("#DeathWormPage").html())
    })
});

Also, put it inside the document ready function or you are referencing a non-existant thing.




回答2:


You can either do:

$("#pageContent").html($("#DeathWormPage").html())

Or

$("#pageContent")[0].innerHTML = $("#DeathWormPage")[0].innerHTML;

The later approach gets you actual DOM element for which innerHTML is available.




回答3:


This works to transfer the content of one div to the other div... good luck


body               { font-size: 16px; line-height: 2em;}
.deathWormButton   { border: 2px solid blue; width: 75px; height: 35px; z-index: 200; font-size: 14px; background-color:#00FF33; }
 


$(function(){
$(".deathWormButton").click(
  function () {
    var htmlStr = $("#pageContent").html();
    $("#DeathWormPage").text(htmlStr);
  }
);
});

 



DeathWorm 


And be one deathWormButton, long I stood  And looked down one as far as I could To where it bent in the undergrowth;
 


ok here-- deathworm button please place content here.
 




回答4:


Using

$("#pageContent").replaceWith($("#DeathWormPage"));

should work as well, and is a little more concise/semantic.



来源:https://stackoverflow.com/questions/4109114/jquery-copying-content-between-divs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!