开发者

Only select a single element that is inside the same element | jQuery selectors

开发者 https://www.devze.com 2022-12-08 02:58 出处:网络
So i have a unordered list, each item in the list has a button that is suppose to toggle the post comment textarea. Unfortunately with my first attempt when u click on one Post Comment button all text

So i have a unordered list, each item in the list has a button that is suppose to toggle the post comment textarea. Unfortunately with my first attempt when u click on one Post Comment button all textareas open, then i tried to use this to make su开发者_JS百科re only one element is selected. Here is the code:

<ul class="todosDisplay">
 <li><span>Content of todo</span><a class="postComment">Post Comment</a>
     <textarea class="showMe"></textarea>
 </li>
<li><span>Content of todo</span><a class="postComment">Post Comment</a>
     <textarea class="showMe"></textarea>
 </li>
<li><span>Content of todo</span><a class="postComment">Post Comment</a>
     <textarea class="showMe"></textarea>
 </li>
 </ul>

And here is my jquery code

$(".postComment").click(function () { 
          $(this).parent().find(".showMe").toggle();
        });

As you can see my poor man's attempt to get to the parent of the ACTUAL element, and then find the element we need to toggle does not work :)

Thanks a lot in advance!


you can use jQuery's $.closest(".showMe") function.


Just built this in Visual Studio and it seems to work. The only thing I noticed with the example above was that the href was missing from the anchor tags resulting in IE not rendering them as links. I added href="#" and your code seemed to work for me. Clicking the link would close the textarea correctly.

<script type="text/javascript">
    $(document).ready(function() {

        $(".postComment").click(function() { $(this).parent().find(".showMe").toggle(); });

    });
</script>

<ul class="todosDisplay">
    <li><span>Content of todo</span><a class="postComment" href="#">Post Comment</a>
        <textarea class="showMe"></textarea>
    </li>
    <li><span>Content of todo</span><a class="postComment" href="#">Post Comment</a>
        <textarea class="showMe"></textarea>
    </li>
    <li><span>Content of todo</span><a class="postComment" href="#">Post Comment</a>
        <textarea class="showMe"></textarea>
    </li>
</ul>


I would suggest changing the jQuery to:

$(".postComment").click(function(){ 
   $(this).siblings(".showMe").toggle();
   return false;
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号