I have a HTML structure like follows
<div id="answer-1">
<a class="edit"></a>
</div>
<div id="answer-2">
<a class="edit"></a>
</div>
<div id="answer-3">
<a class="edit"></a>
</div>
<div id="editor" style="display:none;">
</div>
What i wanna do is when user clicks on the link with a class of edit i will have to hide it's parent div and all subsequent divs having ID like answer-x and have to show the div with the id of editor. I need help with this. This is not not the exact html structure. And the anchor tag with a class of edit may or may not be the immediate child of the div with ID answer-x.It can be in one or two more levels deep inside like
<div id="answer-x">
<div id="hor-list">
<a class="edit"></a>
</div&开发者_高级运维gt;
</div>
So if users clicks on the anchor link inside answer-2 i have to first hide answer-2 and then all answer-x div afterwards.So for the above structure it will be hiding answer-2 and answer-3 div and then showing editor div.
This will hide all divs with an ID that starts with answer-
:
var $answers = $('div[id^=answer-]'),
$editor = $('#editor');
$('a.edit').live('click', function ()
{
$answers.hide();
$editor.show();
});
and this will hide the answer-X
ancestor div of the link that was clicked, and all such subsequent divs:
var $editor = $('#editor');
$('a.edit').live('click', function ()
{
$(this).closest('div[id^=answer-]').hide()
.nextAll('div[id^=answer-]').hide();
$editor.show();
});
The option likely to respond fastest is to give your answer divs a unique class like "answer" and hide all div.answer
following containers, but in the event you can't or don't wish to do that:
$("a.edit").click(function() {
$(this).closest('div[id^="answer-"]').nextAll('div[id^="answer-"]').andSelf().hide();
$("#edit").show();
});
This finds the nearest ancestor with an id starting with "answer-" then finds all sibling elements after that div that meet the same selector and adds the original element to the selection. Then it hides the entire collection.
This comes with one caveat. The answer-x divs all have to be children of the same parent. Otherwise the traversal won't work.
References:
- Attribute Starts With Selector [name^="value"]
- .nextAll()
- .andSelf()
Can you use "answer" as a class name for the div as well? That would simplify things with:
$('a .edit').click(function() {
$(this).closest('.answer').hide().nextAll('.answer').hide();
$('#editor').show();
});
精彩评论