3

我想通过单击图像将 div 的内容替换为另一个 div 的内容(使用 css 隐藏)。但是,使用此处建议的一些方法,我似乎无法使其正常工作。

我的代码如下:

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;
}
4

5 回答 5

4

您只需要设置html()正确的div. 试试这个:

jQuery(document).ready(function() {
    jQuery(".rec1").click(function(event) {
        event.preventDefault() 
        jQuery('#rec-box').html(jQuery(this).next().html()); 
    });
});
于 2013-02-04T10:59:04.670 回答
1
jQuery(document).ready(function() {
    jQuery(".rec1").click(function(event) {
        event.preventDefault() 
        jQuery('#rec-box').html(jQuery("#rec1").html()); 
    });
});
于 2013-02-04T10:59:54.493 回答
1

outerHTML您的原始代码似乎失败了,因为您使用属性(而不是innerHTML)捕获了整个隐藏元素,而不仅仅是其内容。这意味着新复制的内容仍然有<div id='rec1'...>,并且由于 css 规则仍然隐藏。

jQuery 的html方法既可以 get 也可以 set innerHTML,所以这里是正确的方法。

$(document).ready(function () {
  $(".rec1").click(function (event) {
    event.preventDefault();
    $('#rec-box').html($('#rec1').html()); //replaces with contents of #rec1
  });
});
于 2013-02-04T11:00:13.157 回答
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);
});
于 2013-02-04T11:05:11.547 回答
1

你需要$("#rec").contents()得到.clone()

你需要.append()$('#rect-box')拥有.empty()它之后

jQuery(function($) {
    $(".rec1").on('click',function(event) {
        event.preventDefault();
        $('#rec-box').empty().append(($('#rec1').contents().clone());
    });
});
于 2013-12-10T14:22:48.827 回答