我正在尝试构建一个盒子容器,该容器在单击“阅读更多”按钮时展开,并在单击同一按钮时折叠到初始大小(现在是“折叠”按钮)。
在 DOM 中,我在 .post
容器内有一个 .leer-mas
按钮。以及以下 jQuery 代码:
//When link with class .leer-mas is clicked, get the parent element's id and add some css attributes
$('.leer-mas').click(function() {
var item = $(this).closest('.post');
item.css('height', 'auto');
$(this).addClass('leer-menos');
$(this).text('Leer menos');
});
//When link with class .leer-mas is clicked, get the parent element's id and remove some css attributes
$('.leer-mas.leer-menos').click(function() {
var item = $(this).closest('.post');
item.removeAttr('height');
$(this).removeClass('leer-menos');
})
第一个 Action 就像魅力一样。但第二个 Action 什么也没做...而且我认为我错过了 jQuery 的一些基础知识,因为语法是相同的,也许这不是应该的方式:)
有什么想法吗?谢谢。
编辑 - 我的代码有一些错误。虽然我仍在尝试使用单个切换器来获取它,但我已经有了一个工作版本。
新的 DOM 看起来像这样:
<div class="post">
<div class="leer mas">
</div>
<div class="leer menos">
</div>
</div>
代码现在看起来像这样:
//When link with class .leer-mas is clicked, get the parent element's id (which is also that element's id in the database)
$('.leer.mas').click(function() {
var item = $(this).closest('.post');
//Send the id to the PHP script, which returns 1 if successful and 0 if not
item.css('height', 'auto');
$(this).hide();
$(this).next('.leer.menos').show();
});
//When link with class .leer-mas is clicked, get the parent element's id (which is also that element's id in the database)
$('.leer.menos').click(function() {
var item = $(this).closest('.post');
//Send the id to the PHP script, which returns 1 if successful and 0 if not
item.removeAttr('style');
$(this).hide();
$(this).prev('.leer.mas').show();
});
这工作很顺利。但是如果我让它与原始问题的预期结构一起工作(使用单个按钮),我会更高兴:)
最佳答案
这是因为类leer-menos
动态添加...因此,当执行事件注册代码时,不存在具有类 leer-mas
的元素和leer-menos
.
一个可能的解决方案是使用事件委托(delegate)
//When link with class .leer-mas is clicked, get the parent element's id and remove some css attributes
$(document).on('click', '.leer-mas.leer-menos', function() {
var item = $(this).closest('.post');
item.removeAttr('height');
$(this).removeClass('leer-menos');
})
关于javascript - 如何构建一个 jQuery 支持的切换器来添加/删除 css 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18791225/