仅选择同一元素内的单个元素 | jQuery 选择器
所以我有一个无序列表,列表中的每个项目都有一个按钮,用于切换帖子评论文本区域。不幸的是,当我第一次尝试单击一个“发表评论”按钮时,所有文本区域都会打开,然后我尝试使用它来确保只选择一个元素。这是代码:
<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>
这是我的 jquery 代码
$(".postComment").click(function () {
$(this).parent().find(".showMe").toggle();
});
正如你所看到的,我可怜的人试图获取 ACTUAL 元素的父元素,然后找到我们需要切换的元素,但这是行不通的:)
提前非常感谢!
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 sure 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你可以使用 jQuery 的 $.closest(".showMe") 函数。
you can use jQuery's $.closest(".showMe") function.
刚刚在 Visual Studio 中构建了这个,它似乎可以工作。我在上面的示例中注意到的唯一一件事是锚标记中缺少 href,导致 IE 不会将它们呈现为链接。我添加了 href="#" 并且您的代码似乎对我有用。单击该链接将正确关闭文本区域。
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.
我建议将 jQuery 更改为:
I would suggest changing the jQuery to: