jquery class selector capture only the clicked element within the class -
here's demo: https://jsfiddle.net/9fnh6ffy/
here's html:
<p><a href="#" class="new-answer">new answer</a></p> <div class="answer-box"> </div> <p><a href="#" class="new-answer">new answer</a></p> <div class="answer-box"> </div> <p><a href="#" class="new-answer">new answer</a></p> <div class="answer-box"> </div>
i want whenever .new-answer
link clicked, corresponding .answer-box
underneath opened. don't want select relatively such using $(this).parents('p').next().toggle
because don't want problem later debugging if change dom.
since said don't want dom relationship used approach use attribute value. example can use data-id
attribute specify number, same number associated related new-answer
, answer-box
element.
$(document).ready(function() { $('a.new-answer').click(function() { var id = $(this).data('id'); $('.answer-box[data-id="' + id + '"]').toggle(); }); });
.answer-box { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <p><a href="#" class="new-answer" data-id="1">new answer</a></p> <div class="answer-box" data-id="1"></div> <p><a href="#" class="new-answer" data-id="2">new answer</a></p> <div class="answer-box" data-id="2"></div> <p><a href="#" class="new-answer" data-id="3">new answer</a></p> <div class="answer-box" data-id="3"></div>
Comments
Post a Comment