当用户按下按钮时,我使用JQuery来隐藏和显示div。然而,按钮位于另一个div中。我必须遍历树,我认为我做得正确,但我一直收到错误。 Uncaught TypeError: undefined is not a function
。问题是我可以使用......
$( "button.add" ).click(function() {
$('.more-reports').toggle( "slow" );
});
上面的问题是,这会通过一个循环创建这些div的多个实例。所以使用它,可以工作,但会打开所有实例。请参阅下面的调整(这似乎也不起作用。
这是我的页面......
%section.report-library
.container
%br
- @attachments_by_type.each do |type, attachments|
- recent_attachment = attachments.shift
%article.report-container
.report
%ul.inline
%li
%h3= type
%dl
%dd
Uploaded By
%span= recent_attachment.recruiter_name
%dd
•
%dd
= recent_attachment.created_at.strftime("%D %r")
%dd
•
%dd
%button.add#button View previous attachments(This is the button)
%p
= recent_attachment.description
%li
%a.btn.primary{:href => "#{recent_attachment.url}"} Download
.more-reports{:style => "display: none"}(This is the div I am hiding and showing)
- attachments.each do |attachment|
%dl
%dd
Uploaded By
%span=attachment.recruiter_name
%dd
=attachment.created_at.strftime("%D %r")
%dd
%a{:href => "#{attachment.url}"} Download
这是我的JQuery
$( "button.add" ).click(function() {
$(this).parentsUntil('article.report-container').next('.more-reports').toggle( "slow" );
});
我甚至尝试过.parent()。parent()。parent()。parent(),其中包含不同的.parent()。这些似乎都不起作用。
生成的html
<section class='report-library'>
<div class='container'>
<br>
<article class='report-container'>
<div class='report'>
<ul class='inline'>
<li>
<h3>Type B</h3>
<dl>
<dd>
Uploaded By
<span>Brad Martin</span>
</dd>
<dd>
•
</dd>
<dd>
05/22/14 09:24:55 PM
</dd>
<dd>
•
</dd>
<dd>
<button class='add'>View previous attachments</button>
</dd>
</dl>
<p>
Description
</p>
</li>
<li>
<a class='btn primary'>Download</a>
</li>
</ul>
</div>
<div class='more-reports' style='display: none'>
<dd>(Ignore the indentions here. placed in as dummy text)
Uploaded By
<span>Brad Martin</span>
</dd>
<dd>
•
</dd>
<dd>
05/22/14 09:24:55 PM
</dd>
<dd>
•
</dd>
<dd>
<button class='add'>View previous attachments</button>
</dd>
</div>
</article>
<article class='report-container'>
<div class='report'>
<ul class='inline'>
<li>
<h3>Type A</h3>
<dl>
<dd>
Uploaded By
<span>Brad Martin</span>
</dd>
<dd>
•
</dd>
<dd>
05/22/14 08:53:52 PM
</dd>
<dd>
•
</dd>
<dd>
<button class='add'>View previous attachments</button>
</dd>
</dl>
<p>
Description
</p>
</li>
<li>
<a class='btn primary>Download</a>
</li>
</ul>
</div>
<div class='more-reports' style='display: none'>
</div>
</article>
</div>
</section>
答案 0 :(得分:1)
这是你如何做到的;由于.more-reports
是.report-container
的孩子,因此您可以使用.report-container
遍历.closest()
。 parentsUntil()
将匹配多个父母,可能不合适。 .children()
确保您进入一个级别 - 不再进一步。
$(function() {
$( "button.add" ).click( function() {
$(this).closest( '.report-container' ).children('.more-reports').toggle( "slow" );
});
});