用另一个div的内容替换div的内容jQuery
问题描述:
我想通过点击图像来替换另一个div的内容(使用css隐藏)的div的内容。然而,使用这里建议的几个方法,我似乎无法得到它的工作。用另一个div的内容替换div的内容jQuery
我的代码如下:
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;
}
答
你只需要设置正确的。试试这个:
jQuery(document).ready(function() {
jQuery(".rec1").click(function(event) {
event.preventDefault()
jQuery('#rec-box').html(jQuery(this).next().html());
});
});
答
jQuery(document).ready(function() {
jQuery(".rec1").click(function(event) {
event.preventDefault()
jQuery('#rec-box').html(jQuery("#rec1").html());
});
});
答
你原来的代码似乎因为你捕捉整个隐藏的元素,而不仅仅是它的内容,通过使用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
});
});
答
我宁愿以下解决方案:)希望它可以帮助
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);
});
答
你需要得到$("#rec").contents()
和.clone()
它
你需要有.empty()
它
jQuery(function($) {
$(".rec1").on('click',function(event) {
event.preventDefault();
$('#rec-box').empty().append(($('#rec1').contents().clone());
});
});
P.S.后
.append()
它$('#rect-box')
''''是'jQuery'的简写形式,通常更容易阅读,所以请使用它,除非你有命名冲突(即除非其他库已经使用'$') – n*s是的我认为我有冲突,因为只有jQuery作品 – dodgerogers747