jquery切换更改有关状态的图像

我正在使用jquery切换来隐藏一些内容,如果他/她想看到它,用户可以“展开”。 这是一个jsFiddle:

http://jsfiddle.net/yjs2P/

使用此代码:

$.noConflict(); function toggleDiv(divId) { jQuery("#"+divId).toggle($); } 

正如你所看到的那样,第一个元素已经打开了一个“close”-image(红色),另外两个元素被“关闭”了“开放”-images(橙色)。

现在我希望实现这一点,如果用户点击其中一个图像,所有切换元素都会关闭,并且与点击相关的元素会被打开。 打开元素时,图像应该更改为其他状态,因此如果图像关闭(橙色),图像应该更改为打开(红色),反之亦然。

任何人都可以向我提供这个问题的任何提示吗?

提前干杯!

好的,首先让我们对你的html进行一些更改。

让我们不要使用id,而是进入通过类名引用的思维模式。 因此,对于每个内容div,我添加了一个新闻内容

 ... 
...
...
...

接下来让我们从超链接href属性中删除click处理程序(我们将使用jQuery在一分钟内添加一个处理程序)

  

删除了所有的CSS,并确保默认情况下隐藏了新闻内容

 .news-content { display: none; } 

jQuery的

通过这些更改,我们可以为超链接编写一个单击处理程序,以便它执行切换。 注意:我使用slideUpslideDown而不是切换

点击这里查看小提琴

 $(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://sofzh.miximages.com/jquery/toggle-open.jpg'); }); // for the current clicked item either show or hide if ($content.is(':visible')) { $content.slideUp(); $toggleImage.attr('src', 'http://sofzh.miximages.com/jquery/toggle-open.jpg'); } else { $content.slideDown(); $toggleImage.attr('src', 'http://sofzh.miximages.com/jquery/toggle-close.jpg'); } // stop postback return false; }); }); 

更新 – JQuery Handler的新版本

点击这里查看小提琴

 $('a.toggle').click(function () { var openImgUrl = 'http://sofzh.miximages.com/jquery/toggle-open.jpg', closeImgUrl = 'http://sofzh.miximages.com/jquery/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 }); 

试试这个:

 function toggleDiv(divId) { jQuery('[id^=myContent]').not("#" + divId).hide() jQuery("#" + divId).toggle($); var $img = jQuery("#" + divId).next('p').find('img'); var src = $img.attr('src'); $img.attr('src', (src.indexOf('close') > -1) ? src.replace('close', 'open') : src.replace('open', 'close')); } 

在这里演示