使用下面的切换(小提琴),我希望能够执行以下操作:
heading2、content2,但没有成功。这是我的密码:<div>
<span class="heading">This is the beginning of the sentence. </span>
<span class="content">This is the end of the sentence. </span>
</div>CSS
.heading {
cursor: pointer;
}JS
jQuery(document).ready(function () {
jQuery(".content").hide();
//toggle the componenet with class msg_body
$('<a href="#" id="read-more-link">[Read More]</a>').appendTo('.heading');
$('#read-more-link').click(function (e) {
e.preventDefault();
$(this).fadeOut();
$(this).next($(".content").fadeToggle(1000));
});
$('<a href="#" id="close-link">[close]</a>').appendTo('.content');
$('#close-link').click(function (e) {
e.preventDefault();
$(this).fadeOut();
$(this).next($(".content").fadeToggle(1000));
$('<a href="#" id="read-more-link">[Read More]</a>').appendTo('.heading');
});
});发布于 2013-07-01 17:22:33
这里有一个我认为更简单的例子。它减少了DOM中元素的附加和删除:
$(document).ready(function () {
$('.content').after('<a href="#" class="toggle-link">[Read More]</a>');
$(".content").hide();
$('.toggle-link').click(function (e) {
e.preventDefault();
var $link = $(this);
if ($link.data('expanded') == true) {
$link.data('expanded', false);
$link.text('[Read More]');
} else {
$link.data('expanded', true);
$link.text('[Close]');
}
$link.prev(".content").fadeToggle(1000);
});
});发布于 2013-07-01 17:18:17
1-由于您希望在同一个页面上使用多个read多/关闭链接,所以您必须使用类而不是id,因为您不能重复id。
2-要使用类,遍历必须相对于当前元素。
动画需要改进,但是这是一个有用的版本
jQuery(document).ready(function() {
jQuery(".content").hide();
//toggle the componenet with class msg_body
$('<a href="#" class="read-more">[Read More]</a>')
.appendTo('.heading');
$('.read-more').on('click', function(e) {
e.preventDefault();
$(this).fadeOut();
$(this).closest('.heading').next(".content").fadeToggle(1000);
});
$('<a href="#" class="close-link">[close]</a>').appendTo('.content');
$('.close-link').on('click', function(e) {
e.preventDefault();
$(this).closest('.content').fadeToggle(1000)
.prev('.heading').find('.read-more').fadeToggle(1000);
});
});https://stackoverflow.com/questions/17409843
复制相似问题