これはどうですか - まず、html にいくつかの変更を加えましょう。
id を使用せずに、代わりにクラス名で参照するという考え方に入りましょう。そのため、コンテンツ div ごとに、news-contentクラスを追加しました。
...
<div class="news-content" id="myContent">
...
<div class="news-content" id="myContent2">
...
<div class="news-content" id="myContent3">
...
次に、ハイパーリンクの href 属性からクリック ハンドラーを削除します (すぐに jQuery を使用してハンドラーを追加します)。
<a class="toggle" href="#">
すべてのCSSを削除し、ニュースコンテンツがデフォルトで非表示になっていることを確認しました
.news-content {
display: none;
}
jQuery
これらの変更を適用したら、ハイパーリンクのクリック ハンドラーを作成して、トグルを実行できるようにします。注: toggleの代わりにslideUpとslideDownを使用しました。
フィドルはこちら
$(document).ready(function () {
$('a.toggle').click(function () {
// select out the elements for the clicked item
var $this = $(this),
$root = $this.closest('.news-text'),
$content = $root.find('.news-content'),
$toggleImage = $this.find('img');
// collapse all items except the clicked one
$('.news-text').each(function () {
var $itemRoot = $(this);
if ($itemRoot == $root) return; // ignore the current
var $itemContent = $itemRoot.find('.news-content');
if ($itemContent.is(':hidden')) return; // ignore hidden items
// collapse and set img
$itemContent.slideUp();
$itemRoot.find('.toggle > img').attr('src', 'http://www.70hundert.de/images/toggle-open.jpg');
});
// for the current clicked item either show or hide
if ($content.is(':visible')) {
$content.slideUp();
$toggleImage.attr('src', 'http://www.70hundert.de/images/toggle-open.jpg');
} else {
$content.slideDown();
$toggleImage.attr('src', 'http://www.70hundert.de/images/toggle-close.jpg');
}
// stop postback
return false;
});
});
更新 - 新しいバージョンの JQuery ハンドラー
フィドルはこちら
$('a.toggle').click(function () {
var openImgUrl = 'http://www.70hundert.de/images/toggle-open.jpg',
closeImgUrl = 'http://www.70hundert.de/images/toggle-close.jpg';
var $newsItem = $(this).closest('.news-text'),
$newsContent = $newsItem.find('.news-content'),
isContentVisible = ($newsContent.is(':visible'));
// slide up all shown news-items - but its expected that only one is visible at a time
$('.news-text').find('.news-content').slideUp(function () {
// on animation callback change the img
$('.news-text').find('.toggle > img').attr('src', openImgUrl);
});
if (!isContentVisible) { // if the new-item was hidden when clicked, then show it!
$newsContent.slideDown(function () {
// on animation callback change the img
$newsItem.find('.toggle > img').attr('src', closeImgUrl);
});
}
return false; // stop postback
});