jquery中有相邻选择器之类的东西吗?
我正在尝试为这段代码使用正确的选择器,但我似乎无法让它工作。
<ul id="message-list">
<li class="clearfix message success unread">
<a href="/messages/mark_read/61/" class="message-close"></a>
<h4>
<strong>
Getting Real: The Smarter, Faster, Easier Way To Build A Successful Web Application
</strong>
has been added to your profile.
</h4>
<form action="/profile/tweet/NIZNQwAACAAJ/" method="post">
<div style="display:none">
<input type="hidden" value="3b723be17da67c5bc54b27a98a660d53" name="csrfmiddlewaretoken">
</div>
<input type="submit" class="button tweet-button" value="Tweet This Book">
</form>
</li>
</ul>
$('.tweet-button').click(function (e) {
var $list_item = $(this).parent('ul li.message'); < ----- ? ? ?
var $anchor = $(this).parent('a'); // ?? <------
});
我正在尝试获取具有“message”类的最上面列表项的选择器以及与表单相邻的锚标记。
有什么想法吗?
I am trying to use the proper selectors for this code, but I can't seem to get it to work.
<ul id="message-list">
<li class="clearfix message success unread">
<a href="/messages/mark_read/61/" class="message-close"></a>
<h4>
<strong>
Getting Real: The Smarter, Faster, Easier Way To Build A Successful Web Application
</strong>
has been added to your profile.
</h4>
<form action="/profile/tweet/NIZNQwAACAAJ/" method="post">
<div style="display:none">
<input type="hidden" value="3b723be17da67c5bc54b27a98a660d53" name="csrfmiddlewaretoken">
</div>
<input type="submit" class="button tweet-button" value="Tweet This Book">
</form>
</li>
</ul>
$('.tweet-button').click(function (e) {
var $list_item = $(this).parent('ul li.message'); < ----- ? ? ?
var $anchor = $(this).parent('a'); // ?? <------
});
I am trying to get the selector for the uppermost list item with class 'message' and the anchor tag adjacent to the form.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于
li.message
不是按钮的直接祖先,因此请使用.parents ()
搜索 DOM 树,直到到达li.message
:并且由于锚点是
form
的兄弟输入的父级,使用.siblings()
选择.parent()
以获取锚点后:a
与表单不相邻
,尽管它是其同级元素之一。直接在
表单
中嵌套输入
不是有效的HTML。 jQuery 仍然可以使用它,但验证器会抱怨(如果你关心这类事情)。Since
li.message
isn't an immediate ancestor of your button, use.parents()
to search up the DOM tree until you reachli.message
:And since the anchor is a sibling of the
form
parent of your input, use.siblings()
after selecting the.parent()
to get the anchor:By the way,
The
a
isn't adjacent to theform
, although it is one of its sibling elements.Nesting an
input
directly in aform
isn't valid HTML. jQuery will still work with it, but the validator will complain (if you care about that sort of thing).另一种方法是,使用
.closest
并使用.prev
:Another way, using
.closest
and traversing to the anchor using.prev
: