使用jQuery将一个div的内容替换为另一个div的内容

3
我希望通过点击图片将一个 div 标签的内容替换为另一个被用 CSS 隐藏的 div 标签的内容。但是,无论我采用这里建议的一些方法,似乎都不能使它正常工作。
以下是我的代码:
HTML:
<h3>Recent Callaborations</h3>
    <div id="collaborations">
    <img class="rec1" src="http://domain.com/michaelscott/wp-content/uploads/2013/02/url.png"/>
    <div id="rec1">Some image caption that is hidden now and that will replace what is in the rec div below</div>
 </div>

<div id="rec-box" class="rec">
    this is the content that is to be replaced
</div>

js

jQuery(document).ready(function() {
        jQuery(".rec1").click(function(event) {
            event.preventDefault() 
            jQuery('#rec-box').html($(this).next('#rec1')[0].outerHTML); 
          });
        });

css

#collaborations {
    width: 100%;    
    margin:0 0 10px 0;
    padding:0;
}

#collaborations img {
    display:inline-block;
}
.rec {
    background: #EDEDED;
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    padding: 10px;
}
#rec1, #rec2, #rec3, #rec4 {
    display:none;
}
5个回答

4

您只需设置正确的divhtml()即可。试试这个:

jQuery(document).ready(function() {
    jQuery(".rec1").click(function(event) {
        event.preventDefault() 
        jQuery('#rec-box').html(jQuery(this).next().html()); 
    });
});

1
jQuery(document).ready(function() {
    jQuery(".rec1").click(function(event) {
        event.preventDefault() 
        jQuery('#rec-box').html(jQuery("#rec1").html()); 
    });
});

1
您的原始代码似乎失败了,因为您使用 outerHTML 属性(而不是 innerHTML)捕获整个隐藏元素,而不仅仅是其内容。这意味着新复制的内容仍然具有 <div id='rec1'...>,并且由于 CSS 规则仍然处于隐藏状态。
jQuery 的 html 方法可以获取和设置 innerHTML,因此这是正确的方法。
$(document).ready(function () {
  $(".rec1").click(function (event) {
    event.preventDefault();
    $('#rec-box').html($('#rec1').html()); //replaces with contents of #rec1
  });
});

1
P.S. $jQuery 的简写,通常更易阅读,因此除非存在命名冲突(即除非其他库已经使用 $),请使用它。 - nbrooks

1
我更喜欢以下的解决方案 :) 希望能帮到你。 HTML
<h3>Recent Callaborations</h3>
<div id="collaborations">
    <a href="#rec1" class="switchContent"><img class="rec1" src="http://cmagics.eu/michaelscott/wp-content/uploads/2013/02/url.png"/></a>
    <div id="rec1">Some image caption that is hidden now and that will replace what is in the rec div below</div>
 </div>

<div id="rec-box" class="rec">
    this is the content that is to be replaced
</div>

JavaScript

$(document).ready(function() {

    switchContent   =   function(ev) {
        var el  =   $($(this).attr('href'));
        if(el.length == 1) {
            $('#rec-box').html(el.html());
        }
        ev.preventDefault();
    };

    $('.switchContent').on('click',switchContent);
});

1
你需要获取 $("#rec").contents() 并将其 .clone() 在清空 $('#rect-box') 后,你需要 .append() 它。
jQuery(function($) {
    $(".rec1").on('click',function(event) {
        event.preventDefault();
        $('#rec-box').empty().append(($('#rec1').contents().clone());
    });
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接