只获取被点击的元素
Get only the element clicked
我试图让下面的代码工作,但它总是将 class 更改为我拥有的所有 .tog-faq
div,但我无法获得 $(this)
在职的。
我已经尝试过以数千种方式使用 .toggle();
和 .toggleClass()
,但它不起作用。与haml或rails有关系吗?
部分观点:
- @topics.each do |topic|
.title.col-md-4.white-font
.red-back
%h3.white-font= topic.name
%button{class: 'btn btn-sh-grey', id: 'link-panel', onclick: 'ToggleFaq()'}
%span.faq-tog Show
%div.panel-sub.tog-faq.invisible
-if faq_questions(topic).present?
- faq_questions(topic).each do |question|
.faq-con
%h4.panel.panel-heading.item-name.dark-grey= question.questions
当前jquery代码:
function ToggleFaq() {
$('.tog-faq').not(this).addClass('invisible');
$(this).toggleClass('active');
}
css
.invisible {
display: none;
}
.active {
display: block;
}
任何帮助都会很棒!!
没有代码很难检查:
$('tog-faq').click(function() {
$(this).toggleClass('togglingClass');
});
此代码会切换 .tog-faq 元素的 class,如果它被点击
您的 this
没有引用点击的元素。此外,您不应该对多个元素使用相同的 id 属性(因为您在循环中指定了静态 id)。与其使用 HTML 属性 onclick
,使用纯 jQuery 会更容易设置。假设只需要带有 class "btn-sh-grey"
的按钮,您可以执行以下操作:
$.each($('.btn-sh-grey'), function(index, elem) {
$(this).click(function(event) {
$('.faq-tog').removeClass('active').addClass('invisible');
$(this).find('.faq-tog').removeClass('invisible').addClass('active');
});
});
我试图让下面的代码工作,但它总是将 class 更改为我拥有的所有 .tog-faq
div,但我无法获得 $(this)
在职的。
我已经尝试过以数千种方式使用 .toggle();
和 .toggleClass()
,但它不起作用。与haml或rails有关系吗?
部分观点:
- @topics.each do |topic|
.title.col-md-4.white-font
.red-back
%h3.white-font= topic.name
%button{class: 'btn btn-sh-grey', id: 'link-panel', onclick: 'ToggleFaq()'}
%span.faq-tog Show
%div.panel-sub.tog-faq.invisible
-if faq_questions(topic).present?
- faq_questions(topic).each do |question|
.faq-con
%h4.panel.panel-heading.item-name.dark-grey= question.questions
当前jquery代码:
function ToggleFaq() {
$('.tog-faq').not(this).addClass('invisible');
$(this).toggleClass('active');
}
css
.invisible {
display: none;
}
.active {
display: block;
}
任何帮助都会很棒!!
没有代码很难检查:
$('tog-faq').click(function() {
$(this).toggleClass('togglingClass');
});
此代码会切换 .tog-faq 元素的 class,如果它被点击
您的 this
没有引用点击的元素。此外,您不应该对多个元素使用相同的 id 属性(因为您在循环中指定了静态 id)。与其使用 HTML 属性 onclick
,使用纯 jQuery 会更容易设置。假设只需要带有 class "btn-sh-grey"
的按钮,您可以执行以下操作:
$.each($('.btn-sh-grey'), function(index, elem) {
$(this).click(function(event) {
$('.faq-tog').removeClass('active').addClass('invisible');
$(this).find('.faq-tog').removeClass('invisible').addClass('active');
});
});