Replacing the content of a div with the content of another hidden div in Jquery
i am trying to replace the content of a div with the content of another div(which is hidden).开发者_StackOverflow The code works for the first time only but the second time doesn't work at all. I have a div where the titles of some articles are scrolling. I want to achieve that:everytime i am going to click the title of an article its content(the content is in hidden div) is going to appear in another div with the id="sreen".
<script type="text/javascript">
//everytime you click the title of an article
$("a.title").live("click", function(){
//replace the content of div screen with the content of an article
$('div#screen').replaceWith($(this).next('div.content'));
});
</script>
Any ideas???
Using .replaceWith
will effectively remove div#screen
. So using .html()
will be what you want to do to maintain the element div#screen
.
You mentioned that your formating is not working correctly which leads me to believe you have css classes on div.content
. Calling .html()
on div.content
will ommit the root node of div.content.
<div class="content">
<span>some text</span>
</div>
$("div.content").html()
will produce <span>some text</span>
If my assumptions are correct you might want to look at using clone()
which will clone the current object without events or clone(true)
to include any data and events.
var $content = $(this).next('div.content').clone();
$content.css("display", "block");
$('div#screen').html($content);
Another way of doing this would be use .outerHTML
$("a.title").live("click", function() {
$('div#screen').html($(this).next('div.content')[0].outerHTML);
});
Example on jsfiddle.
use the .html
docs method for this
<script type="text/javascript">
//everytime you click the title of an article
$("a.title").live("click", function(){
//replace the content of div screen with the content of an article
$('div#screen').html( $(this).next('div.content').html() );
});
</script>
精彩评论