使用 jQuery 切换博客文章(展开/折叠)
在我的博客中,有些文章很长。所以我希望长文章在页面加载时折叠起来。它只适用于我的一篇文章,但如果我有更多文章,某些东西似乎会被破坏。
我是这样做的:
$('div#ttoggle').hide();
$('#btoggle').click( function() {
if($('div#btoggle p').text() == 'expand article'){
$('div#btoggle p').text('collapse article');
}else{
$('div#btoggle p').text('expand article');
}
$('div#ttoggle').slideToggle("slow");
});
有什么想法吗?
in my blog some articles are very long. So I want the long articles to be collapsed when the page is loaded. It works for me for just one article but if I have more articles something seems to be broken.
Here's how I do it:
$('div#ttoggle').hide();
$('#btoggle').click( function() {
if($('div#btoggle p').text() == 'expand article'){
$('div#btoggle p').text('collapse article');
}else{
$('div#btoggle p').text('expand article');
}
$('div#ttoggle').slideToggle("slow");
});
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您似乎正在使用
id
选择器来表示您声明将在页面上多次出现的内容。id
属性必须是唯一的,因此这将是无效的 HTML,并可能导致失败。这里的解决方案是将所有
id
替换为class
。您可以使用.classname
选择器来选择适当的元素You seem to be using an
id
selector for something which you state will appear multiple times on the page.id
attributes must be unique, so this would be invalid HTML and could be causing this to fail.The solution here would be to replace all
id
s withclass
es. You can use the.classname
selector to select the appropriate elements您正在使用 ids“#btoggle”,您可能需要类。您应该只拥有一个具有给定 id 的元素。
您将点击处理程序分配给多个元素,然后通过重新检查所有元素来决定要做什么。相反,在处理程序中使用
this
来仅考虑单击的元素:(我不知道您的 HTML 实际上是什么样子,我对兄弟姐妹进行了猜测。)
You are using ids "#btoggle" where you probably want classes. You should only ever have a single element with a given id.
You are assigning a click handler to a number of elements, but then deciding what to do by examining all the element afresh. Instead use
this
inside your handler to only consider the clicked element:(I don't know what your HTML actually looks like, I took a guess at the siblings.)