开发者

put content of div1 into div2 onclick event

开发者 https://www.devze.com 2023-04-10 23:02 出处:网络
I have two divs as follows: <div id=\'div1\'> <p>Hello world!</p> </div> <div id=\'div2\'>

I have two divs as follows:

<div id='div1'>
    <p>Hello world!</p>
</div>

<div id='div2'>

</div>

<a id='test' href='javascript:void()'>Click me to fill in 开发者_StackOverflow中文版div2</a>

I have been wondering what should be the best way to fill in div2 with the content of div1 onclick using jquery in order to have

<div id='div1'>
        <p>Hello world!</p>
    </div>


Append a clone of the contents of $("#div1") to $("#div2") using .contents(), .clone(), and .append():

$("#div2").append($("#div1").contents().clone());


Rather than resorting to serialising to HTML and then applying that to the other element, as Andy's answer does, it would be nicer to clone the nodes.

$('#test').click(function(e) {
    e.preventDefault();
    $('#div1').contents().clone(true).appendTo('#div2');
});

This has the advantage that any data or events on the elements cloned will continue to exist on the new elements. Since I've used e.preventDefault(), you can also lose the javascript:void bit of your code, because the link's default action has been prevented.

See the jQuery API:

  • contents
  • clone
  • appendTo
  • event.preventDefault


$('#div2').html($('#div1').html());
0

精彩评论

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

关注公众号