用Jquery中另一个隐藏div的内容替换div的内容

时间:2011-02-10 20:52:13

标签: javascript jquery

我正在尝试用另一个div(隐藏)的内容替换div的内容。该代码仅在第一次工作,但第二次根本不起作用。 我有一个div,其中一些文章的标题是滚动。我希望实现这一目标:每次我要点击文章的标题时,其内容(内容在隐藏的div中)将出现在另一个div中,其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>

任何想法???

2 个答案:

答案 0 :(得分:4)

使用.replaceWith将有效删除div#screen。因此,使用.html()将是您要维护元素div#screen

的目的

你提到你的格式化工作不正常导致我相信你在div.content上有css课程。在.html()上调用div.content将省略div.content的根节点。

<div class="content">
 <span>some text</span>
</div>

$("div.content").html()将生成<span>some text</span>

如果我的假设是正确的,您可能希望使用clone()来克隆没有事件的当前对象,或clone(true)包含任何数据和事件。

var $content = $(this).next('div.content').clone();
$content.css("display", "block");
$('div#screen').html($content);

另一种方法是使用.outerHTML

$("a.title").live("click", function() {
  $('div#screen').html($(this).next('div.content')[0].outerHTML); 
});

jsfiddle上的示例。

答案 1 :(得分:0)

使用.htmldocs方法进行此

<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>