开发者

How to replace inner html of one <div> to another </div> through jquery

I have two div tags: one contain an img tag inside and the other contain something else.

My first <div> contains an image. When I click on that image, or on some <div> having id insideFrameimg, it should show the second <div id="insideFra开发者_如何学JAVAmeobj" style="display:none;"> in place of <div id="insideFrameimg">.

<div id="insideFrameimg"><!-- first div-->
  <img src="my-image.png"/>
<div>

<div id="insideFrameobj"> <!--second div -->
  hello this is my description
</div>

I want to show the complete inner html of <div id="insideFrameobj"> in place of the first <div> when I click on <img> found inside the <div id="insideFrameimg"> using jQuery.


<div id="insideFrameimg"><!-- first div-->
  <img id="imgClick" src=""/>
  <div>

  <div id="insideFrameobj"> <!--second div -->
       hello this is my description>
   </div>

Something like this should help. It will replace first div content with second div content.

$('#imgClick').click(function () {
 $('#insideFrameimg').html($('#insideFrameobj').html());

});


You can use the children function to get all children of insideFrameobj and use the append function to move them to insideFrameimg. That would typically be better than using innerHTML (or its jQuery wrapper html) because you're not tearing down the elements and recreating them (which would lose their event handlers). It's also more efficient.

That would look something like this:

$("#insideFrameimg").click(function() {
    $(this).append($("#insideFrameobj").children());
});

Naturally this leaves insideFrameobj empty, which seems to be what you want. If you don't, you might clone the children and append the clones:

$("#insideFrameimg").click(function() {
    $(this).append($("#insideFrameobj").children().clone());
//                           difference is here ---^
});

But if any of the children have id values, cloning them and adding the clones will result in an invalid document, since ids must be unique. (This is not just a theoretical issue; it will cause trouble for your page, if you ever use those IDs.)


Just replace the contents of the div when the img is clicked:

$('#insideFrameimg img').click(function() {
    var contents = $('#insideFrameobj').html();
    $('#insideFrameimg').html(contents);
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜